android内存优化方法,Android开发内存优化注意事项和方法
在Android的實際開發(fā)中,可能會出現(xiàn)不再使用的對象無法被系統(tǒng)回收的情況,這種情況會導(dǎo)致內(nèi)存泄漏,甚至內(nèi)存溢出,導(dǎo)致程序崩潰。
檢測方法:使用LeakCanary
優(yōu)化方案:
1.檢查使用多少內(nèi)存
每個 APP 的堆(heap)內(nèi)存大小有硬性限制,如果您的 APP 已達到堆內(nèi)存限制,并嘗試分配更多的內(nèi)存,系統(tǒng)會拋出 OutOfMemoryError 。為了避免 OOM ,您可以查詢當前設(shè)備有多少堆空間,可以通過調(diào)用系統(tǒng) getMemoryInfo() 查詢,返回 一個ActivityManager.MemoryInfo 對象,它提供該設(shè)備當前存儲器的狀態(tài)信息,包括可用的存儲器,總存儲器,和低于該閾值存儲器。
private void getMemoryInfo() {
ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
LogUtil.d("totalMem=" + memoryInfo.totalMem + ",availMem=" + memoryInfo.availMem); if (!memoryInfo.lowMemory) { // 運行在低內(nèi)存環(huán)境 }
}123456789123456789
2.當界面不可見時釋放內(nèi)存
實現(xiàn) ComponentCallbacks2 API 中 onTrimMemory()) ,當回調(diào)參數(shù) level 為 TRIM_MEMORY_UI_HIDDEN ,是用戶點擊了Home鍵或者Back鍵退出應(yīng)用,所有UI界面被隱藏,這時候應(yīng)該釋放一些不可見的時候非必須的資源。
public class MainActivity extends AppCompatActivity implements ComponentCallbacks2 { // Other activity code ... /**
* Release memory when the UI becomes hidden or when system resources become low.
* @param level the memory-related event that was raised.
*/ public void onTrimMemory(int level) { // Determine which lifecycle or system event was raised. switch (level) { case ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN: /*
Release any UI objects that currently hold memory.
The user interface has moved to the background.
*/ break; case ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE: case ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW: case ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL: /*
Release any memory that your app doesn't need to run.
The device is running low on memory while the app is running.
The event raised indicates the severity of the memory-related event.
If the event is TRIM_MEMORY_RUNNING_CRITICAL, then the system will
begin killing background processes.
*/ break; case ComponentCallbacks2.TRIM_MEMORY_BACKGROUND: case ComponentCallbacks2.TRIM_MEMORY_MODERATE: case ComponentCallbacks2.TRIM_MEMORY_COMPLETE: /*
Release as much memory as the process can.
The app is on the LRU list and the system is running low on memory.
The event raised indicates where the app sits within the LRU list.
If the event is TRIM_MEMORY_COMPLETE, the process will be one of
the first to be terminated.
*/ break; default: /*
Release any non-critical data structures.
The app received an unrecognized memory level value
from the system. Treat this as a generic low-memory message.
*/ break;
}
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
該 onTrimMemory() 回調(diào)是在搭載Android 4.0(API級別14)加入。對于早期版本,您可以使用 onLowMemory() 回調(diào)作為舊版本的回調(diào),這大致相當于 TRIM_MEMORY_COMPLETE事件。
3.謹慎使用服務(wù)
離開了 APP 還在運行服務(wù)是最糟糕的內(nèi)存管理錯誤之一,當 APP 處在后臺,我們應(yīng)該停止服務(wù),除非它需要運行的任務(wù)。我們可以使用 JobScheduler 替代實現(xiàn),JobScheduler 把一些不是特別緊急的任務(wù)放到更合適的時機批量處理。如果必須使用一個服務(wù),最佳方法是使用 IntentService ,限制服務(wù)壽命,所有請求處理完成后,IntentService 會自動停止。
4.使用優(yōu)化的數(shù)據(jù)容器
考慮使用優(yōu)化過數(shù)據(jù)的容器 SparseArray / SparseBooleanArray / LongSparseArray 代替 HashMap 等傳統(tǒng)數(shù)據(jù)結(jié)構(gòu),通用 HashMap 的實現(xiàn)可以說是相當?shù)托У膬?nèi)存,因為它需要為每個映射一個單獨的條目對象。
5.避免在Android上使用枚舉
6.使用 nano protobufs 序列化數(shù)據(jù)
Protocol buffers 是一個語言中立,平臺中立的,可擴展的機制,由谷歌進行序列化結(jié)構(gòu)化數(shù)據(jù),類似于 XML 設(shè)計的,但是更小,更快,更簡單。如果需要為您的數(shù)據(jù)序列化與協(xié)議化,建議使用 nano protobufs。
7.避免內(nèi)存流失
8.使用ProGuard來剔除不需要的代碼
使用 ProGuard 來剔除不需要的代碼,移除任何冗余的,不必要的,或臃腫的組件,資源或庫完善 APP 的內(nèi)存消耗。
9.減少apk體積
您可以通過減少 APP 的整體規(guī)模顯著減少 APP 的內(nèi)存使用情況。文章:Android APK瘦身實踐
10.優(yōu)化布局層次
通過優(yōu)化視圖層次結(jié)構(gòu),以減少重疊的 UI 對象的數(shù)量來提高性能。文章:Android 渲染優(yōu)化
11.使用 Dagger 2依賴注入
依賴注入框架可以簡化您寫的代碼,并提供一個自適應(yīng)環(huán)境測試和便于其他配置的更改。如果打算在您的 APP 使用依賴注入框架,可以考慮用 Dagger 2 ,Dagger 不使用反射掃描 APP 的代碼,Dagger 是靜態(tài)的,意味著它編譯時不需要占用運行 Android 應(yīng)用或內(nèi)存的使用。
12.小心使用外部庫
13.避免Bitmap浪費
Bitmap是內(nèi)存消耗的大頭,當使用時要及時回收。另外配置:
inSampleSize:縮放比例,圖片按需加載,避免不必要的大圖載入。
decode format:解碼格式,選擇ARGB_8888/RBG_565/ARGB_4444/ALPHA_8,存在很大差異。
14.Cursor關(guān)閉
如查詢數(shù)據(jù)庫的操作,使用到Cursor,也要對Cursor對象及時關(guān)閉。
15.監(jiān)聽器的注銷
Android程序里面存在很多需要register與unregister的監(jiān)聽器,手動add的listener,需要記得及時remove這個listener。
總結(jié)
以上是生活随笔為你收集整理的android内存优化方法,Android开发内存优化注意事项和方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux shared,从 0 开始学
- 下一篇: android m版本 root,And