The code
that causes the memory leak is as follows: I believe everyone can see it and wrote some pseudo-code
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//todo 这里做一些事情。。。
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(new Runnable() {
@Override
public void run() {
SystemClock.sleep(3000);
Message msg = new Message();
msg.what = 3;
handler.sendMessage(msg);
}
}).start();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
In this case, when you exit the software, the thread is executing and still holds a reference to the activity, which will cause a memory leak
Solution code: It is not weak drinking, please refer to it,
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//todo 这里做一些事情。。。
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(new Runnable() {
@Override
public void run() {
SystemClock.sleep(3000);
Message msg = new Message();
msg.what = 3;
//这里是修改点
if (handler != null){
handler.sendMessage(msg);
}
}
}).start();
}
@Override
protected void onDestroy() {
super.onDestroy();
//注意这里是修改点
handler.removeCallbacksAndMessages(null);
handler = null;
//第二种写法 把message 全局变量
//message.recycle();
}
Why write it like this?