26 November 2017
Handler class should be static or leaks might occur Android
Handler类应该是static类型,否则有可能造成泄露。
public class MyHandler extends Handler{
WeakReference<Activity> mActivity;
MyHandler(Activity activity){
mActivity = new WeakReference<Activity>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Activity activity = mActivity.get();
if (activity == null){
return;
}
switch (msg.what) {
default:break;
}
}
}
Activity会被gc掉,如果Activity被回收掉,那么Handler应该在使用之前对其状态进行判断,这样就不会发生空指针。
— Kong Jing