避免使用Handler而造成的内存泄漏
作者:
苏简笔记 | 来源:发表于
2016-05-19 20:06 被阅读45次
原文链接
public class SampleActivity extends Activity { /** * Instances of static inner classes do not hold an implicit * reference to their outer class. */
private static class MyHandler extends Handler { private final WeakReference mActivity; public MyHandler(SampleActivity activity) { mActivity = new WeakReference(activity); } @Override public void handleMessage(Message msg) { SampleActivity activity = mActivity.get(); if (activity != null) { // ... } } } private final MyHandler mHandler = new MyHandler(this); /** * Instances of anonymous classes do not hold an implicit * reference to their outer class when they are static. */ private static final Runnable sRunnable = new Runnable() { @Override public void run() { /* ... */ } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Post a message and delay its execution for 10 minutes. mHandler.postDelayed(sRunnable, 1000 * 60 * 10); // Go back to the previous Activity. finish(); }}
本文标题:避免使用Handler而造成的内存泄漏
本文链接:https://www.haomeiwen.com/subject/qhpgrttx.html
网友评论