Problem: Use Handler handler = new Handler() to generate asynchronous network data in the activity, and call the handler multiple times to cause the activity to be destroyed
HandleMessage 还能调用 activity中的方法多次跳转目标页面。
Reason: Activity uses an anonymous inner class to cause the handler class object to hold the activity reference, which leads to memory overflow, and the activity is not recycled. So you think the destroyed activity is still there.
Solution: Create a custom interface and a custom handler class. Decoupling activity and handler. The handler uses WeakReference to obtain a weak reference to the activity interface. When the activity needs to be recycled, it is no longer affected by the handler.
interface:
public interface OnHandlerCallBack {
public void mHandleMessage(Message msg);
}
handler class:
public class LoginHandler extends Handler {
private WeakReference<OnHandlerCallBack> mactivity;
public LoginHandler(OnHandlerCallBack activity){
mactivity=new WeakReference<OnHandlerCallBack>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
OnHandlerCallBack callBack =mactivity.get();
if(callBack!=null){
callBack.mHandleMessage(msg);
}
}
}
1. Inherit and implement the interface in the activity
implements OnHandlerCallBack
//统一通信 登录线程切换
@Override
public void mHandleMessage(Message msg) {
hideLoading();
if (msg.what == 0) {
//存储密码,跳转到主页面
} else {
ToastUtil.showShort(mContext, "FECK登录失败:" + msg.obj.toString());
}
}
2. The handler calls:
new LoginHandler(this::mHandleMessage)
problem solved.