Android手机给应用分配的内存通常是8兆左右,如果处理内存处理不当很容易造成OutOfMemoryError OutOfMemoryError主要由以下几种情况造成:
Cursor没关。 close()释放资源。Adapter没有使用缓存convertView。registerReceiver()和unregisterReceiver()要成对出现,通常需要在Activity的onDestory()方法去取消注册广播接收者。private static Drawable sBackground; @Override protected void onCreate(Bundle state) { super.onCreate(state); TextView label = new TextView(this); label.setText("Leaks are bad"); if (sBackground == null) { sBackground = getDrawable(R.drawable.large_bitmap); } label.setBackgroundDrawable(sBackground); setContentView(label); }
这段代码效率很快,但同时又是极其错误的: Drawable拥有一个TextView的引用,而TextView又拥有Activity(Context类型)的引用,Drawable拥有了更多的对象引用。即使Activity被销毁,内存仍然不会被释放。
另外,对Context的引用超过它本身的生命周期,也会导致Context泄漏。所以尽量使用Application这种Context类型。所以如果打算保存一个长时间的对象时,要使用getApplicationContext()。
最近遇到一种情况引起了Context泄漏,就是在Activity销毁时,里面有其他线程没有停。总结一下避免Context泄漏应该注意的问题:
getApplicationContext()类型。Context的引用不要超过它本身的生命周期。static关键字。Context里如果有线程,一定要在onDestroy()里及时停掉。
原文:http://www.cnblogs.com/huangzx/p/4479696.html