本文介绍了处理器和内存泄漏的Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请看看下面的code:
Please have a look at the code below:
public class MyGridFragment extends Fragment{
Handler myhandler = new Handler() {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case 2: {
ArrayList<HashMap<String,String>> theurls = (ArrayList<HashMap<String,String>>) message.obj;
urls.addAll(theurls);
theimageAdapter.notifyDataSetChanged();
dismissBusyDialog();
break;
}}}};
}
当我使用的处理程序是这样,我得到一个警告处理程序应该是静态的,否则很容易出现内存泄漏。谁能告诉我什么是做到这一点的最好方法是什么?
When I use handler like this I get a warning "handler should be static, else it is prone to memory leaks." Can someone tell me what is the best way to do this?
推荐答案
我最近更新了自己的code类似的东西。我只是做匿名处理程序类受保护的内部类和皮棉警告走了。看看像下面code会为你工作:
I recently updated something similar in my own code. I just made the anonymous Handler class a protected inner class and the Lint warning went away. See if something like the below code will work for you:
public class MyGridFragment extends Fragment{
static class MyInnerHandler extends Handler{
WeakReference<MyGridFragment> mFrag;
MyInnerHandler(MyGridFragment aFragment) {
mFrag = new WeakReference<MyGridFragment>(aFragment);
}
@Override
public void handleMessage(Message message) {
MyGridFragment theFrag = mFrag.get();
switch (message.what) {
case 2:
ArrayList<HashMap<String,String>> theurls = (ArrayList<HashMap<String,String>>) message.obj;
theFrag.urls.addAll(theurls);
theFrag.theimageAdapter.notifyDataSetChanged();
theFrag.dismissBusyDialog();
break;
}//end switch
}
}
MyInnerHandler myHandler = new MyInnerHandler(this);
}
您可能需要更改的地方,我把theFrag。我只能猜测,什么这些引用。
You may have to change where I put "theFrag." as I could only guess as to what those referenced.
这篇关于处理器和内存泄漏的Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!