This Handler class should be static or leaks might occur.

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<SplashActivity> mActivity;
 6         
 7         SplashHandler(SplashActivity activity) {
 8             mActivity = new WeakReference<SplashActivity>(activity);
 9         }
10         
11         public void handleMessage(Message msg) {
12             // TODO Auto-generated method stub
13             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     @Override
28     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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值