Analysis and Solution of Memory leakage caused by Handler in Android
The internal class of Handler holds the reference of the external class Activity. If the Activity exits and the Handler still has delayed message processing is not completed, the Activity cannot be recycled. Repeated operations will lead to memory leakage.
Solution 1: clear messages when onDestroy is enabled. mHandler. removeCallbacksAndMessages (null); // If the parameter is null, all messages are cleared.
Solution 2: declare Handler as static and hold weak reference of Activity. Key: the comments in the program
public class MainActivity extends Activity { private static final String tag = "MainActivity"; private TextView mTvShow; private MyHandler mHandler; private static final int DELAY_TIME = 10000; // set to 5s and 10s to check result. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHandler = new MyHandler(MainActivity.this); Log.e(tag, "onCreate"); mTvShow = (TextView)findViewById(R.id.tv_show); new Thread() { @Override public void run() { mHandler.sendEmptyMessageDelayed(1, DELAY_TIME); Log.e(tag, "msg send"); } }.start(); } @Override protected void onDestroy() { Log.e(tag, "onDestroy"); super.onDestroy(); } static class MyHandler extends Handler{ WeakReference
mWeakActivity; public MyHandler(MainActivity activity) { mWeakActivity = new WeakReference<>(activity); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); MainActivity activity = mWeakActivity.get(); Log.e(tag, "handleMessage," + msg.what); // 5s is not null, 10s is null, tell that activity is recycled. if(null == activity){ Log.e(tag, "null"); }else{ Log.e(tag, "not null"); activity.mTvShow.setText("delay show"); } } }}