android - Handler 内存泄露问题
PHP中文网
PHP中文网 2017-04-17 17:32:35
0
3
447

请问这种写法会不会导致内存泄露:

       static class MyHandler extends Handler {
        WeakReference<Activity> mWeakReference = null;

        public MyHandler(SampleActivity activity) {
            mWeakReference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SampleActivity activity = (SampleActivity) mWeakReference.get();
            if(activity == null) {
                return;
            } else {
                if(msg.what == 0) {
                    //do something
                }
            }
        }
    }

然后我在onCreate方法中初始化一个MyHandler的对象:

    private MyHandler mHandler = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
        mHandler = new MyHandler(this);
    }
PHP中文网
PHP中文网

认证0级讲师

reply all(3)
伊谢尔伦

No, this is the standard way to use weak references.

刘奇

You don’t need weak references. Just clear the message when destroying

Ty80

The original poster should pay attention to Google’s official demo and lint tips

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template