Android 中 Handler的正确写法

1.错误示范

        以前写Handler的时候,是直接这样写的:

  Handler mHandler = new Handler(){
    @Override
    public void dispatchMessage(Message msg) {
      switch (msg.what){
         xxx;
      }
    }
  };

        然后 Android Studio就会贴心的提醒你:

This Handler class should be static or leaks might occur (anonymous android.os.Handler) 

错误的含义就是说,这样写有可能造成内存泄漏,因为当Handler所在的组件消亡时,它可能继续存在,造成内存泄漏。

2.正确写法

    private static class MyHandler extends Handler {
 
        private WeakReference activityWeakReference;
 
        public MyHandler(MyActivityactivity) {
            activityWeakReference = new WeakReference<>(activity);
        }
 
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MyActivity activity = activityWeakReference.get();
            if (activity != null) {
               //处理handler消息
            }
        }
    }

 

正确的写法是,使用静态内部类的形式,配合弱引用,当宿主主键销毁时,做一下判断。

你可能感兴趣的:(Android)