This Handler class should be static or leaks might occur Android

 更新到ADT2.0的开发者们可能会在handler上发现这么一条警告:This Handler class should be static or leaks might occur 。
          首先在ADT 20 Changes我们可以找到这样一个变化:New Lint Checks:

          Look for handler leaks: This check makes sure that a handler inner class does not hold an implicit reference to its outer class.

首先解释下这句话This Handler class should be static or leaks might occur,大致意思就是说:Handler类应该定义成静态类,否则可能导致内存泄露。

 

具体如何解决,在国外有人提出,如下:

Issue: Ensures that Handler classes do not hold on to a reference to an outer class

In Android, Handler classes should be static or leaks might occur. Messages enqueued on the application thread's MessageQueue also retain their target Handler. If the Handler is an inner class, its outer class will be retained as well. To avoid leaking the outer class, declare the Handler as a static nested class with a WeakReference to its outer class.

大体翻译如下:

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

使用范例:

static class MyHandler extends Handler {
                WeakReference<PopupActivity> mActivity;

                MyHandler(PopupActivity activity) {
                        mActivity = new WeakReference<PopupActivity>(activity);
                }

                @Override
                public void handleMessage(Message msg) {
                        PopupActivity theActivity = mActivity.get();
                        switch (msg.what) {
                        case 0:
                                theActivity.popPlay.setChecked(true);
                                break;
                        }
                }
        };

        MyHandler ttsHandler = new MyHandler(this);
        private Cursor mCursor;

        private void test() {
                ttsHandler.sendEmptyMessage(0);
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值