Android手机给应用分配的内存通常是8兆左右,如果处理内存处理不当很容易造成OutOfMemoryError 
OutOfMemoryError主要由以下几种情况造成:

  1. 数据库Cursor没关。 
    当我们操作完数据库后,一定要调用close()释放资源。
  2. 构造Adapter没有使用缓存convertView。
  3. 未取消注册广播接收者,registerReceiver()unregisterReceiver()要成对出现,通常需要在ActivityonDestory()方法去取消注册广播接收者。
  4. IO流未关闭 
    注意用完后及时关闭
  5. Bitmap使用后未调用recycle()。
  6. Context泄漏。 这是一个很隐晦的OutOfMemoryError的情况。先看一个Android官网提供的例子
    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()里及时停掉。

 

posted on 2015-05-05 17:09  道无涯  阅读(190)  评论(0编辑  收藏  举报