本文主要是介绍This Handler class should be static or leaks maight occur,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在使用Handler更新UI的时候出现警告:
意思是说:这个Handler 必须是static的,否则就会引发内存泄露。
解决:
让Handler持有一个对Activity的WeakReference,这样就不会泄露Activity的上下文了:
public class TestActivity extends AppCompatActivity {private final MyHandler mMyHandler = new MyHandler(this);@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);mMyHandler.postDelayed(new Runnable() {@Overridepublic void run() {// TODO: 2018/3/2 }}, 60 * 10 * 1000);}private static class MyHandler extends Handler {private WeakReference<TestActivity> mWeakReference = null;private MyHandler(TestActivity activity) {mWeakReference = new WeakReference<TestActivity>(activity);}@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);TestActivity activity = mWeakReference.get();if (activity != null) {// TODO: 2018/3/2}}}
}
这篇关于This Handler class should be static or leaks maight occur的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!