Android: This Handler class should be static or leaks might occur

0x00

private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0: mTextView.setText("msg received"); break; } } };

以往我习惯这样改变Android的UI,但是Android Studio Warning:
This Handler class should be static or leaks might occur.

0x01

原因比较简单,msg发送的时候有一个delayed参数,如果在delayed参数以内该activity被destory了,但是mHandler还持有mContext等待接收消息,所以会引发内存泄漏。

0x02

solve idea:

private final MyHandler mHandler = new MyHandler(this); private static class MyHandler extends Handler { private final WeakReference mVideoFragment; public MyHandler(VideoFragment m) { mVideoFragment = new WeakReference(m); } @Override public void handleMessage(Message msg) { VideoFragment m = mVideoFragment.get(); if (m != null) { switch (msg.what) { case 0: m.mTextView.setText("msg received"); break; default:break; } } }}

你可能感兴趣的:(Android: This Handler class should be static or leaks might occur)