这个处理程序类应该是静态的或可能发生泄漏:最后的处理程序 [英] This Handler class should be static or leaks might occur: final Handler
本文介绍了这个处理程序类应该是静态的或可能发生泄漏:最后的处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在$ C C的Eclipse $下面生成警告这个处理程序类应该是静态的或可能发生泄漏。
On below code Eclipse generate warning "This Handler class should be static or leaks might occur".
public class MyActivity extends Activity implements Runnable
{
final Handler handler = new Handler()
{
@Override
public void handleMessage( Message message)
{
String sResult = (String) message.obj;
if( (sResult != null) && (sResult != ""))
{
MyNonStatic = (TableLayout) findViewById( R.id.tableLayout); // any non-static method
}
return;
}
};
public void run()
{
final Message message = handler.obtainMessage( 1, MyFunction( context));
handler.sendMessage( message);
}
public String MyFunction( Context context)
{
return "MyNewString";
}
}
我回顾许多议题上的网站,但没有得到解决方案。请帮我这个code?
I review many topics on site, but not get solution. Please help me for this code?
补充:我需要调用非静态方法(例如findViewById())中的handleMessage()
Add: i need call non-static method (for example findViewById()) in handleMessage()!
推荐答案
下面是一个使用弱引用和静态处理程序类来解决这个问题的一个例子作为建议皮棉文档中:
Here is an example of using a weak reference and static handler class to resolve the problem as recommended in the Lint documentation:
public class MyClass{
//static inner class doesn't hold an implicit reference to the outer class
private static class MyHandler extends Handler {
//Using a weak reference means you won't prevent garbage collection
private final WeakReference<MyClass> myClassWeakReference;
public MyHandler(MyClass myClassInstance) {
myClassWeakReference = new WeakReference<MyClass>(myClassInstance);
}
@Override
public void handleMessage(Message msg) {
MyClass myClass = myClassWeakReference.get();
if (myClass != null) {
...do work here...
}
}
}
private final MyHandler mHandler = new MyHandler(this);
public void getHandler() {
return new MyHandler(this);
}
}
这篇关于这个处理程序类应该是静态的或可能发生泄漏:最后的处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文