Android内存泄漏问题
程序员文章站
2024-01-11 08:56:58
1,静态变量导致的内存泄漏
在dalvik虚拟机中,static变量所指向的内存引用,如果不把它设置为null,GC【garbage collection
】是永远不会回收...
1,静态变量导致的内存泄漏
在dalvik虚拟机中,static变量所指向的内存引用,如果不把它设置为null,GC【garbage collection
】是永远不会回收这个对象的,所以会导致这个activity无法正常销毁:
public class MainActivity extends Activity{ private static Context mContext; @ovveride proteced void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; } }
那么怎么解决呢,将 mContext赋为 null 就可以了。
public class MainActivity extends Activity{ private static Context mContext; @override proteced void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; } @override proteced void onDestroy() super.onDestroy(); if(mContext != null){ mContext = null; } }
2,单例模式导致的内存泄漏
下面提供一个单例模式的类:
public class SingleInstanceF { private static SingleInstanceF single; private Context context; private SingleInstanceF(Context context){ this.context = context; } public static SingleInstanceF getInstance(Context context){ if(single==null){ single = new SingleInstanceF(context); } return single; } }
接着来使用这个单例模式:
public class TestActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SingleInstanceF instanceF = SingleInstanceF.getInstance(this); } }
TestActivity对象被单利模式所引用,同样当退出activity时activity得不到释放。
解决方法:在onDestroy()将instance赋值为null。或者将参数 this 换成 application context。
3,属性动画造成的内存泄漏
public class MainActivity extends Activity{ ObjectAnimator animator; Button mButton; @override proteced void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button1); animator = ObjectAnimator.ofFloat(mButton, "rotation", 0, 360).setDuration(2000); animator.setRepeatCount(ValueAnimator.INFINITE); animator.start(); } }
因为动画在无限循环,如果在Activity中播放这个动画并且没有在onDestroy中去停止这个动画,那么动画会一直播放下去
,尽管无法在界面上看到动画效果了,并且这个时候Activity的View会被动画持有,而View又持有 Activity,最终Activity
无法释放。解决方法,在onDestroy中调用 animator.cancle()来停止动画:
public class MainActivity extends Activity{ ObjectAnimator animator; Button mButton; @override proteced void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button1); animator = ObjectAnimator.ofFloat(mButton, "rotation", 0, 360).setDuration(2000); animator.setRepeatCount(ValueAnimator.INFINITE); animator.start(); } @override void onDestroy(){ super.onDestroy(); animator.cancle(); }