Android -- 內存泄漏


Android為不同類型的進程分配了不同的內存使用上限,如果應用進程使用的內存超過了這個上限,則會被系統視為內存泄漏,從而被kill掉。Android為應用進程分配的內存上限如下所示:

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

# 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后沒有關閉的情況。如果我們的查詢結果集比較小,對內存的消耗不容易被發現,只有在常時間大量操作的情況下才會復現內存問題,這樣就會給以后的測試和問題排查帶來困難和風險。

示例代碼:

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                             

以構造ListView的BaseAdapter為例,在BaseAdapter中提高了方法:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM