Android解決記憶體溢出問題

來源:互聯網
上載者:User

標籤:

eoeandroid 推薦:
android避免記憶體溢出
http://www.eoeandroid.com/thread-180008-1-1.html
Android 記憶體溢出的解決辦法
http://www.eoeandroid.com/thread-66415-1-1.html


1. 當項目中包含大量圖片,或者圖片過大
方法1:等比例縮小圖片
  1. BitmapFactory.Options options = new BitmapFactory.Options();  
  2. options.inSampleSize = 4
複製代碼方法2:對圖片採用軟引用,及時地進行recyle()操作

  1. SoftReference<Bitmap> bitmap;  
  2. bitmap = new SoftReference<Bitmap>(pBitmap);  
  3. if(bitmap != null){  
  4. if(bitmap.get() != null && !bitmap.get().isRecycled()){ 
  5.       bitmap.get().recycle();  
  6.     bitmap = null; 
  7.     }  
  8.    } 
複製代碼方法3 : 對複雜的listview進行合理設計與編碼(個人感覺這個靠譜點)1. 注意重用Adapter裡面的convertView,以及holder機制的運用
----- 參考資料: api demo list 14. Efficient Adapter

2. 上述方法嘗試還未成功,可用 lazy loading data 
----- 參考資料: api demo list 13
  1. public View getView(int position, View convertView, ViewGroup parent) { 
  2. if (convertView == null) {  
  3.             v = mInflater.inflate(resource, parent, false); 
  4.          final int[] to = mTo;  
  5.         final int count = to.length; 
  6.        final View[] holder = new View[count];  
  7.            for (int i = 0; i < count; i++) {  
  8.              holder[i] = v.findViewById(to[i]); 
  9.     }  
  10.          v.setTag(holder);       } else {  
  11.    }  
  12. }
複製代碼方法4 : 單個頁面,橫豎屏切換N次後 OOM
1. 看看頁面配置當中有沒有大的圖片,比如背景圖之類的。去除xml中相關設定,改在程式中設定背景圖(放在onCreate()方法中):
  1. Drawable bg = getResources().getDrawable(R.drawable.bg); 
  2. XXX.setBackgroundDrawable(rlAdDetailone_bg);  
複製代碼在Activity destory時注意,bg.setCallback(null); 防止Activity得不到及時的釋放。
2. 跟上面方法相似,直接把xml設定檔載入成view 再放到一個容器裡,然後直接調用 this.setContentView(View view);避免xml的重複載入。

方法5:在頁面切換時儘可能少地重複使用一些代碼。比如:重複調用資料庫,反覆使用某些對象等等.....

方法6:Android堆記憶體也可以自己定義大小和最佳化Dalvik虛擬機器的記憶體
--參考資料:http://blog.csdn.net/wenhaiyan/article/details/5519567

  • 注意:若使用這種方法:project build target 只能選擇 <= 2.2 版本,否則編譯將通不過。 所以不建議用這種方式。
  1. private final static int CWJ_HEAP_SIZE= 6*1024*1024;  
  2. private final static float TARGET_HEAP_UTILIZATION = 0.75f;   
  3. VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);  
  4. VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 
複製代碼
本帖地址:   http://www.eoeandroid.com/thread-198865-1-1.html  [複製連結]

Android解決記憶體溢出問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.