Android Handler 内存泄漏问题

1. 内存泄漏的Activity

public class MainActivity extends AppCompatActivity {

  private static final int MESSAGE_TYPE1 = 10;
  private Button mBtnSendMessage;
  private TextView mTvShow;
  private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      switch (msg.what) {
        case MESSAGE_TYPE1:
          mTvShow.setText("hhh");
          break;

      }
    }
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mBtnSendMessage = findViewById(R.id.btn_go_second);
    mTvShow = findViewById(R.id.tv_show);
    mBtnSendMessage.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Message msg = Message.obtain();
        msg.what = MESSAGE_TYPE1;
      // 直接发送,没啥问题
        mHandler.sendMessage(msg);
      //   延迟发送,如果Activity已经销毁,内存泄漏
        mHandler.sendMessageDelayed(msg,1000*60*5);
      }
    });
  }
}

分析:Main线程中 有一个Message 持有者Handler的引用,而且Handler持有外部类MainActivity的应用,所以产生了内存泄漏。MainActivity没有被及时的释放掉。

LeakCanary的内存泄漏截图

Screenshot_20180811-175135.jpg

2. 无内存泄漏的Handler

public class MainActivity extends AppCompatActivity {

  private static final int MESSAGE_TYPE1 = 10;
  private Button mBtnSendMessage;
  private TextView mTvShow;
  private SuperHandler mHandler = new SuperHandler(this);

  private static class SuperHandler extends Handler {
    private final WeakReference mActivity;

    private SuperHandler(MainActivity activity) {
      mActivity = new WeakReference<>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
      switch (msg.what) {
        case MESSAGE_TYPE1: {
          MainActivity activity = mActivity.get();
          if(activity != null) {
            activity.setTvShowText("hhh");
          }
        }
      }
      // end handleMessage
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mBtnSendMessage = findViewById(R.id.btn_go_second);
    mTvShow = findViewById(R.id.tv_show);
    mBtnSendMessage.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Message msg = Message.obtain();
        msg.what = MESSAGE_TYPE1;
//        mHandler.sendMessage(msg);
        mHandler.sendMessageDelayed(msg,1000*60*5);
      }
    });
  }


  public void setTvShowText(String text) {
    mTvShow.setText(text);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    // 移除所有的消息队列
    mHandler.removeCallbacksAndMessages(null);
  }
}

分析:和原来的不同之处在于这里采用了静态内部类的形式 来实现了一个SuperHandler,这样SuperHandler就不会持有MainActivity的引用。在Activity的OnDestroy结束之后,弱引用mActivity的值就get出来就为空了。

OnDestroy中移除掉消息池中的消息,完事

继续看下Handler的removeCallbacksAndMessages的源码我们可以发现
Handler 关联绑定一个Queue,通过调用queue.removeCallbacksAndMessages移除所有target为当前Handler的message。

    void removeCallbacksAndMessages(Handler h, Object object) {
        if (h == null) {
            return;
        }

        synchronized (this) {
            Message p = mMessages;

            // Remove all messages at front.
            while (p != null && p.target == h
                    && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }

            // Remove all messages after front.
            while (p != null) {
                Message n = p.next;
                if (n != null) { 
                   // 目标为当前对象,则移除
                    if (n.target == h && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

最后稍微理一下Handler、Looper、Message的关系

  • Handler:内部包含Looper中的Queue,以及handleMessage的方法(没有设置任何回调接口的情况下才会使用)
  • Message:一般通过obtain()方法获得一个Message,消息池中如果有消息可以复用,没有就会新建。Message.target指向的是一个Handler
  • Looper:持有消息队列,会调用Handler的dispatchMessage方法(有回调用回调,没有则调用handleMessage方法),并且这个Handler是唯一的,因为Message中有target属性指向Handler

如有错误欢迎指正,谢谢!


参考文献:

https://blog.csdn.net/javazejian/article/details/50839443

你可能感兴趣的:(Android Handler 内存泄漏问题)