標籤:android des style blog http java
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