内存泄漏(转)

Android为不一样类型的进程分配了不一样的内存使用上限,若是应用进程使用的内存超过了这个上限,则会被系统视为内存泄漏,从而被kill掉。Android为应用进程分配的内存上限以下所示:java

位置: /ANDROID_SOURCE/system/core/rootdir/init.rc 部分脚本android

复制代码
# Define the oom_adj values for the classes of processes that can be
# killed by the kernel.  These are used in ActivityManagerService.
    setprop ro.FOREGROUND_APP_ADJ 0
    setprop ro.VISIBLE_APP_ADJ 1
    setprop ro.SECONDARY_SERVER_ADJ 2
    setprop ro.BACKUP_APP_ADJ 2
    setprop ro.HOME_APP_ADJ 4
    setprop ro.HIDDEN_APP_MIN_ADJ 7
    setprop ro.CONTENT_PROVIDER_ADJ 14
    setprop ro.EMPTY_APP_ADJ 15
 
# Define the memory thresholds at which the above process classes will
# be killed.  These numbers are in pages (4k).
    setprop ro.FOREGROUND_APP_MEM 1536
    setprop ro.VISIBLE_APP_MEM 2048
    setprop ro.SECONDARY_SERVER_MEM 4096
    setprop ro.BACKUP_APP_MEM 4096
    setprop ro.HOME_APP_MEM 4096
    setprop ro.HIDDEN_APP_MEM 5120
    setprop ro.CONTENT_PROVIDER_MEM 5632
    setprop ro.EMPTY_APP_MEM 6144
 
# Write value must be consistent with the above properties.
# Note that the driver only supports 6 slots, so we have HOME_APP at the
# same memory level as services.
    write /sys/module/lowmemorykiller/parameters/adj 0,1,2,7,14,15
 
    write /proc/sys/vm/overcommit_memory 1
    write /proc/sys/vm/min_free_order_shift 4
    write /sys/module/lowmemorykiller/parameters/minfree 1536,2048,4096,5120,5632,6144
 
    # Set init its forked children's oom_adj.
    write /proc/1/oom_adj -16
复制代码

正由于咱们的应用程序可以使用的内存有限,因此在编写代码的时候须要特别注意内存使用问题。以下是一些常见的内存使用不当的状况。数据库

查询数据库没有关闭游标                                                                缓存

程序中常常会进行查询数据库的操做,可是常常会有使用完毕Cursor后没有关闭的状况。若是咱们的查询结果集比较小,对内存的消耗不容易被发现,只有在常时间大量操做的状况下才会复现内存问题,这样就会给之后的测试和问题排查带来困难和风险。布局

示例代码:post

Cursor cursor = getContentResolver().query(uri ...);
if (cursor.moveToNext()) {
    ... ... 
}

修正示例代码:测试

复制代码
Cursor cursor = null;
try {
    cursor = getContentResolver().query(uri ...);
    if (cursor != null && cursor.moveToNext()) {
        ... ... 
    }
} finally {
    if (cursor != null) {
        try { 
            cursor.close();
        } catch (Exception e) {
            //ignore this
        }
    }
}
复制代码

构造Adapter时,没有使用缓存的 convertView                             this

以构造ListView的BaseAdapter为例,在BaseAdapter中提升了方法:spa

public View getView(int position, View convertView, ViewGroup parent)线程

来向ListView提供每个item所须要的view对象。初始时ListView会从BaseAdapter中根据当前的屏幕布局实例化必定数量的view对象,同时ListView会将这些view对象缓存起来。当向上滚动ListView时,原先位于最上面的list item的view对象会被回收,而后被用来构造新出现的最下面的list item。这个构造过程就是由getView()方法完成的,getView()的第二个形参 View convertView就是被缓存起来的list item的view对象(初始化时缓存中没有view对象则convertView是null)。

    由此能够看出,若是咱们不去使用convertView,而是每次都在getView()中从新实例化一个View对象的话,即浪费资源也浪费时间,也会使得内存占用愈来愈大。ListView回收list item的view对象的过程能够查看:

android.widget.AbsListView.java --> void addScrapView(View scrap) 方法。

示例代码:

public View getView(int position, View convertView, ViewGroup parent) {
    View view = new Xxx(...);
    ... ...
    return view;
}

修正示例代码:

复制代码
public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;
    if (convertView != null) {
        view = convertView;
        populate(view, getItem(position));
        ...
    } else {
        view = new Xxx(...);
        ...
    }
    return view;
}
复制代码

Bitmap对象不在使用时调用recycle()释放内存                                

有时咱们会手工的操做Bitmap对象,若是一个Bitmap对象比较占内存,当它不在被使用的时候,能够调用Bitmap.recycle()方法回收此对象的像素所占用的内存,但这不是必须的,视状况而定。能够看一下代码中的注释:

复制代码
/**
     * Free up the memory associated with this bitmap's pixels, and mark the
     * bitmap as "dead", meaning it will throw an exception if getPixels() or
     * setPixels() is called, and will draw nothing. This operation cannot be
     * reversed, so it should only be called if you are sure there are no
     * further uses for the bitmap. This is an advanced call, and normally need
     * not be called, since the normal GC process will free up this memory when
     * there are no more references to this bitmap.
     */
复制代码

释放对象的引用                                                                             

这种状况描述起来比较麻烦,举两个例子进行说明。

示例A:

假设有以下操做

复制代码
public class DemoActivity extends Activity {
    ... ...
    private Handler mHandler = ...
    private Object obj;
    public void operation() {
     obj = initObj();
     ...
     [Mark]
     mHandler.post(new Runnable() {
            public void run() {
             useObj(obj);
            }
     });
    }
}
复制代码

咱们有一个成员变量 obj,在operation()中咱们但愿可以将处理obj实例的操做post到某个线程的MessageQueue中。在以上的代码中,即使是mHandler所在的线程使用完了obj所引用的对象,但这个对象仍然不会被垃圾回收掉,由于DemoActivity.obj还保有这个对象的引用。因此若是在DemoActivity中再也不使用这个对象了,能够在[Mark]的位置释放对象的引用,而代码能够修改成:

复制代码
... ...
public void operation() {
    obj = initObj();
    ...
    final Object o = obj;
    obj = null;
    mHandler.post(new Runnable() {
        public void run() {
            useObj(o);
        }
    }
}
... ...
复制代码

示例B:

    假设咱们但愿在锁屏界面(LockScreen)中,监听系统中的电话服务以获取一些信息(如信号强度等),则能够在LockScreen中定义一个PhoneStateListener的对象,同时将它注册到TelephonyManager服务中。对于LockScreen对象,当须要显示锁屏界面的时候就会建立一个LockScreen对象,而当锁屏界面消失的时候LockScreen对象就会被释放掉。

    可是若是在释放LockScreen对象的时候忘记取消咱们以前注册的PhoneStateListener对象,则会致使LockScreen没法被垃圾回收。若是不断的使锁屏界面显示和消失,则最终会因为大量的LockScreen对象没有办法被回收而引发OutOfMemory,使得system_process进程挂掉。

    总之当一个生命周期较短的对象A,被一个生命周期较长的对象B保有其引用的状况下,在A的生命周期结束时,要在B中清除掉对A的引用。

其余                                                                                           

   Android应用程序中最典型的须要注意释放资源的状况是在Activity的生命周期中,在onPause()、onStop()、onDestroy()方法中须要适当的释放资源的状况。

我是天王盖地虎的分割线                                                                 

参考:http://rayleeya.iteye.com/blog/727074