This Handler class should be static or leaks might occur

5,292 views

出现This Handler class should be static or leaks might occur警告的原因是如下:

Handler类应该应该为static类型,否则有可能造成泄露。在程序消息队列中排队的消息保持了对目标Handler类的应用。如果Handler是个内部类,那么它也会保持它所在的外部类的引用。为了避免泄露这个外部类,应该将Handler声明为static嵌套类,并且使用对外部类的弱应用。

就是说Handler得类声明必须声明为static的嵌套类。
例如常用的Hander用法如下:

import android.os.Handler;
import android.os.Message;

public class Temp extends Thread{

MyHandler handler=new MyHandler();

@Override
public void run() {
// TODO Auto-generated method stub
super.run();
int what=0;
handler.sendEmptyMessage(what);
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
int what = msg.what;
switch (what) {
case 0:
System.out.println("retult=0");
break;
case 1:
System.out.println("retult=1");
break;
default:
System.out.println("error");
break;
}
}
}
}

没有声明为static类,就会提示This Handler class should be static or leaks might occur的警告。所以在MyHandler 加上static关键字即可。即

static class MyHandler extends Handler{……}

这就意味着直接使用下面方式Handler实现内部类也会提示警告。

Handler handler=new Handler(){
//内部实现
};

因此也需要加上静态变量static:

static Handler handler=new Handler(){
//内部实现
};

这也意味着相关的函数和变量也要改变。
又或者这样的方式

Handler  handler= new MyHandler(){
//内部实现
};
static class MyHandler extends Handler{
//空类
}

即上面类改为:

import android.os.Handler;
import android.os.Message;

public class Temp extends Thread{

Handler handler=new MyHandler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
int what = msg.what;
switch (what) {
case 0:
System.out.println("retult=0");
break;
case 1:
System.out.println("retult=1");
break;
default:
System.out.println("error");
break;
}
}
};

@Override
public void run() {
// TODO Auto-generated method stub
super.run();
int what=0;
handler.sendEmptyMessage(what);
}
static class MyHandler extends Handler{}
}

 

This entry was posted in android, android 异常 and tagged by Charlie. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>