错误如图所示,大概意思是Handler类需要被静态修饰否则导致内存泄漏。
解决方案:采用弱引用的方式解决问题。
static class MyHandler extends Handler{
WeakReference<MainActivity> mActivity;//此处泛型填写Myhandler所在的外部类,也就是所在的Activity
MyHandler(MainActivity mainActivity){
mActivity = new WeakReference<>(mainActivity);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity = mActivity.get();
switch (msg.what){
case 1:
activity.textView.setText("我开始慌了!");
a = 2;
break;
case 2:
activity.textView.setText("我开始困了!");
a = 1;
break;
default:
break;
}
}
}
MyHandler handler = new MyHandler(this);//实例化类
Message message = new Message();
message.what = a;
handler.sendMessage(message);//传递message