package cc.cc; import android.os.Bundle; import android.app.Activity; /** * Demo描述: * 非静态内部类可能导致的内存泄露及其优化 * * 在MainActivity中定义了两个内部类InnerClassTest和ThreadSubClass. * 在这里需要注意一个问题: * 内部类持有外部类的引用!!!! * 或者说内部类对外部类持有隐式的引用!!!! * * 假如我们在内部类中做耗时的操作或者说有个while(true)死循环,即内部类的对象一直存在; * 那么当这个MainActivity应该被回收时(比如屏幕的旋转)GC发现它还被其内部类的对象引用 * 所以就不会将其回收.假如该Activity中含有大量的资源(比如图片)那么就很容易发生OOM. * * 优化方式: * 使用静态的内部类,这样的内部类就不会持有外部类的隐式引用;也就不会影响到GC对于外部类的回收 * * * 参考资料: * 1 http://blog.csdn.net/guolin_blog/article/details/42238633 * 2 http://blog.csdn.net/tu_bingbing/article/details/10395129 * 3 http://blog.csdn.net/zhangjg_blog/article/details/20000769 * 4 http://blog.csdn.net/zhongwcool/article/details/22886067 * 5 http://foolog.net/wap/index-wap2.php?p=2550 * 6 http://blog.csdn.net/theone10211024/article/details/45645309 * 7 http://blog.csdn.net/tu_bingbing/article/details/10350533 * 8 http://www.eoeandroid.com/thread-571279-1-1.html * 9 http://2dxgujun.com/post/2014/09/11/Handler-Leaks-Solution.html * Thank you very much * */ public class MainActivity extends Activity { private BetterThread mBetterThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } private void init(){ mBetterThread=new BetterThread(); mBetterThread.start(); } //定义一个内部类 private class InnerClassTest { private InnerClassTest() { } private void methodA() { //Activity activity=MainActivity.this; } private void methodB() { } } //定义一个内部类 private class ThreadSubClass extends Thread{ @Override public void run() { super.run(); //Activity activity=MainActivity.this; } } //优化后的方式 private static class BetterThread extends Thread { private boolean isRunning = true; @Override public void run() { super.run(); while(isRunning){ //doing something } } public void stopThread(){ isRunning=false; } } //停止线程 @Override protected void onDestroy() { mBetterThread.stopThread(); super.onDestroy(); } }
时间: 2024-10-06 08:19:58