gpt4 book ai didi

java - 此处理程序类应该是静态的,否则可能会发生泄漏 : final Handler

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:16:36 25 4
gpt4 key购买 nike

在下面的代码中,Eclipse 生成警告“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";
}
}

我在网站上查看了很多主题,但没有找到解决方案。请帮助我获取此代码?

补充:我需要在handleMessage()中调用非静态方法(例如findViewById())!

最佳答案

下面是一个使用弱引用和静态处理程序类来解决 Lint 文档中推荐的问题的示例:

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 MyHandler getHandler() {
return new MyHandler(this);
}
}

关于java - 此处理程序类应该是静态的,否则可能会发生泄漏 : final Handler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13507208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com