提示信息:
This Handler class should be static or leaks might occur (anonymous android.os.Handler)
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类应该是静态的,否则可能会发生泄漏(匿名android.os.Handler)由于此Handler被声明为内部类,因此可能会阻止外部类被垃圾回收。如果Handler使用Looper或MessageQueue作为主线程以外的线程,则没有问题。如果Handler正在使用主线程的Looper或MessageQueue,则需要修复Handler声明,如下所示:将Handler声明为静态类;在外部类中,实例化外部类的WeakReference,并在实例化Handler时将此对象传递给Handler;使用WeakReference对象对外部类的成员进行所有引用。
产生问题的原因:
在子线程中使用Handler
public class LooperThread extends Thread {
public Handler handler; //声明一个Handler对象 ,此处Handler被声明为内部类
private int mid;
TextView mview;
public LooperThread(int id,TextView view){
this.mid=id;
this.mview=view;
}
@Override
public void run() {
super.run();
Looper.prepare(); //初始化Looper对象
Handler handler=new Handler()
{
public void handleMessage(Message msg){
switch (msg.what){
case 0x22:{
if(mid==R.id.btn_send_02){
mview.setText("子线程中使用Handler");
Log.i("关于子线程:","子线程中Handler启动");
Log.i("子线程Looper.myLooper","="+Looper.myLooper());
}
}
}
}
};
Message message=handler.obtainMessage(); //获取一个消息
message.what=0x22;
handler.sendMessage(message);
Looper.loop();
}
}
解决方式:
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
//使用handleMessage
return false;
}
});
修改原程序:
public class LooperThread extends Thread {
public Handler handler; //声明一个Handler对象
private int mid;
TextView mview;
public LooperThread(int id,TextView view){
this.mid=id;
this.mview=view;
}
@Override
public void run() {
super.run();
Looper.prepare(); //初始化Looper对象
//实例化一个Handler对象
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case 0x22:{
if(mid==R.id.btn_send_02){
mview.setText("子线程中使用Handler");
Log.i("关于子线程:","子线程中Handler启动");
Log.i("子线程Looper.myLooper","="+Looper.myLooper());
}
}
}
return false;
}
});
Message message=handler.obtainMessage(); //获取一个消息
message.what=0x22;
handler.sendMessage(message);
Looper.loop();
}
}