在activity中使用handler,ide会显示一个警告
This Handler class should be static or leaks might occur
意思是handler应用static修饰否则容易发生内存泄漏
我们又不能将handler声明成static然后将所有的成员变量都变成final,所以我们可以在activity创建一个匿名的handler, 然后让这个handler持有activity的若引用即可
class DemoHandler<T> extends Handler
{
private WeakReference<T> mActivity;
public DemoHandler(T activity)
{
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg)
{
T activity = mActivity.get();
super.handleMessage(msg);
switch (msg.what)
{
case 0:
activity.getClass().getName();
LogUtils.i("send in static handel");
break;
}
}
}
网友评论