今天遇到的问题,mark一下
错误提示:
This Handler class should be static or leaks might occur
(全类名)
Issue: Ensures that Handler classes do not hold on to a reference to an outer class
Id: HandlerLeak
Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.
[]
错误的意思大致就是说:Handler类应该定义成静态类,否则可能导致内存泄露。在程序消息队列中排队的消息保持了对目标Handler类的应用。如果Handler是个内部类,那 么它也会保持它所在的外部类的引用。为了避免泄露这个外部类,应该将Handler声明为static嵌套类,并且使用对外部类的弱应用。
第一种方法:把Handler定义成static,然后用post方法把Runnable对象传送到主线程,代码如下:
private TextView tvName;
private static Handler myHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvName = (TextView) findViewById(R.id.tv_name);
myHandler=new Handler();
myHandler.post(myRunnable);//使用handler将Runnable放到主线程执行
}
Runnable myRunnable=new Runnable() {
@Override
public void run() {
//将原来handler中要做的操作放到Runnable中
tvName.setText("Demo");
}
};
这种方法将要执行的操作放到了Runable对象中,再将Runable放到主线程执行,此方法适用于只有一个消息要发送的情况。
第二种方法:先定义一个static的内部类MyHandler继承Handler类,然后让它持有Activity的弱引用,代码如下:
private TextView tvName;
private static MyHandler myHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvName = (TextView) findViewById(R.id.tv_name);
myHandler = new MyHandler(this);
myHandler.sendEmptyMessage(1);
}
private static class MyHandler extends Handler {
WeakReference<MainActivity> reference;
public MyHandler(MainActivity mainActivity) {
this.reference = new WeakReference<MainActivity>(mainActivity);// 给弱引用赋值
}
@Override
public void handleMessage(Message msg) {
MainActivity mainActivity=reference.get();//获取到引用的Activity
if (mainActivity == null) {//判断下看Activity是否被回收
return;
}
switch (msg.what) {//根据不同的消息执行不同的代码
case 0:
mainActivity.tvName.setText("Demo");
break;
case 1:
mainActivity.tvName.setText("Test");
break;
}
super.handleMessage(msg);
}
}