关于内存泄漏的一些点

这篇博客讲的非常棒

http://www.jb51.net/article/92311.htm


总结几点:

        1、非静态内部类默认会持有外部类的引用,所以如果此时设置一个内部类为静态变量的时候,外部类将会无法被GC。

        2、匿名类造成的泄漏原因和上面一样。

        3、由于 Handler 属于 TLS(Thread Local Storage) 变量, 生命周期和 Activity 是不一致的。因此这种实现方式一般很难保证跟 View 或者 Activity 的生命周期保持一致,故很容易导致无法正确释放。

比如:

    

public class SampleActivity extends Activity {

private final Handler mLeakyHandler = new Handler() {

@Override

public void handleMessage(Message msg) {

// ...

}

}

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Post a message and delay its execution for 10 minutes.

mLeakyHandler.postDelayed(new Runnable() {

@Override

public void run() { /* ... */ }

}, 1000 * 60 * 10);

// Go back to the previous Activity.

finish();

}

}


在10秒内,如果activity调用finish。

延迟执行任务的 Message 还会继续存在于主线程中,它持有该 Activity 的 Handler 引用,所以此时 finish() 掉的 Activity 就不会被回收了从而造成内存泄漏(因 Handler 为非静态内部类,它会持有外部类的引用,在这里就是指 SampleActivity)。


有一个解决办法就是使用静态static和软引用:

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<SampleActivity> mActivity;

public MyHandler(SampleActivity activity) {

mActivity = new WeakReference<SampleActivity>(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();

}

}

















posted @ 2017-04-05 19:24  _如此甚好  阅读(136)  评论(0编辑  收藏  举报