博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
This Handler class should be static or leaks might occur.
阅读量:5940 次
发布时间:2019-06-19

本文共 2202 字,大约阅读时间需要 7 分钟。

This Handler class should be static or leaks might occur. 大概意思是:Handler类应该定义成静态类,否则可能导致内存泄露。

查询资料,比较统一的解决方法如下所示:

Handler objects for the same thread all share a common Looper object, which they post messages to and read from.

As messages contain target Handler, as long as there are messages with target handler in the message queue, the handler cannot be garbage collected. If handler is not static, your Activity cannot be garbage collected, even after being destroyed.

This may lead to memory leaks, for some time at least - as long as the messages stay int the queue. This is not much of an issue unless you post long delayed messages.

So, you can make your Handler static and have a WeakReference to your Activity.

也就是说:

Handler类应该应该为static类型,否则有可能造成泄露。在程序消息队列中排队的消息保持了对目标Handler类的应用。如果Handler是个内部类,那么它也会保持它所在的外部类的引用。为了避免泄露这个外部类,应该将Handler声明为static嵌套类,并且使用对外部类的弱应用。

eg:

1 public class SplashActivity extends Activity { 2      3     static class SplashHandler extends Handler { 4          5         WeakReference
mActivity; 6 7 SplashHandler(SplashActivity activity) { 8 mActivity = new WeakReference
(activity); 9 }10 11 public void handleMessage(Message msg) {12 // TODO Auto-generated method stub13 switch (msg.what) {14 case 0:15 Intent intent = new Intent();16 intent.setClass(mActivity.get(), MainActivity.class);17 mActivity.get().startActivity(intent);18 mActivity.get().finish();19 break;20 default:21 break;22 }23 super.handleMessage(msg);24 }25 } 26 27 @Override28 protected void onCreate(Bundle savedInstanceState) {29 super.onCreate(savedInstanceState);30 requestWindowFeature(Window.FEATURE_NO_TITLE);31 setContentView(R.layout.activity_splash);32 33 SplashHandler mSplashHandler = new SplashHandler(this);34 mSplashHandler.sendEmptyMessageDelayed(0, 2000);35 }36 }

 

转载于:https://www.cnblogs.com/lulinan/p/3175029.html

你可能感兴趣的文章
软件工程之构建之法
查看>>
UVa 10902
查看>>
Mathf.Sin正弦
查看>>
禁止浏览器缓存js
查看>>
【Redis】安装PHP的redis驱动(二)
查看>>
java中string和int互相转化
查看>>
什么是序列化,为什么要序列化
查看>>
Java保留小数点后有效数字
查看>>
新学期的合作
查看>>
C++中一些类和数据结构的大小的总结
查看>>
mysql开启binlog
查看>>
ctrl + z fg bg
查看>>
工作流引擎Oozie(一):workflow
查看>>
struct框架
查看>>
Deep Learning(深度学习)相关网站
查看>>
设置Eclipse编码方式
查看>>
分布式系统唯一ID生成方案汇总【转】
查看>>
Cross-compilation using Clang
查看>>
营销系统--手动补偿
查看>>
图标字体设计
查看>>