android.os.handler包,GitHub - deyunvip/android-weak-handler: Memory safer implementation of android.o...

本文介绍了Android中Handler的内存泄漏问题及其解决方案——WeakHandler。Handler在默认实现时会保留对处理对象的硬引用,可能导致内存泄漏。WeakHandler通过保持对Runnable和Message的弱引用,解决了这一问题。当WeakHandler不再被引用时,GC可以回收相关资源。使用WeakHandler只需在构建文件中添加依赖,并像普通Handler一样使用。 WeakHandler由Badoo公司发布,遵循MIT许可证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android Weak Handler

Memory safer implementation of android.os.Handler

Problem

Original implementation of Handler always keeps hard reference to handler in queue of execution.

Any object in Message or Runnable posted to android.os.Handler will be hard referenced for some time.

If you create anonymous Runnable and call to postDelayed with large timeout, that Runnable will be held

in memory until timeout passes. Even if your Runnable seems small, it indirectly references owner class,

which is usually something as big as Activity or Fragment.

You can read more on our blog post.

Solution

WeakHandler is trickier then android.os.Handler , it will keep WeakReferences to runnables and messages,

and GC could collect them once WeakHandler instance is not referenced any more.

b8c4aa5fdc553923f5a2f747b01748f3.png

Usage

Add reference to your build.gradle:

repositories {

maven {

repositories {

url 'https://oss.sonatype.org/content/repositories/releases/'

}

}

}

dependencies {

compile 'com.badoo.mobile:android-weak-handler:1.1'

}

Use WeakHandler as you normally would use Handler

import com.badoo.mobile.util.WeakHandler;

public class ExampleActivity extends Activity {

private WeakHandler mHandler; // We still need at least one hard reference to WeakHandler

protected void onCreate(Bundle savedInstanceState) {

mHandler = new WeakHandler();

...

}

private void onClick(View view) {

mHandler.postDelayed(new Runnable() {

view.setVisibility(View.INVISIBLE);

}, 5000);

}

}

Credits

Weak Handler is brought to you by Badoo Trading Limited and it is released under the MIT License.

##Blog

Read more on our tech blog or explore our other open source projects

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值