2015年11月22日 星期日

Android 實戰記錄 (1) - java.lang.OutOfMemoryError


這次遇到OutOfMemory  問題

可能原因在於導覽頁或說明頁,跳出滿版的圖片
而圖片大小是1080X1920,約10幾K才會
但經過decode成Bitmap後,可能就變成不止10幾K

原使用以下方式取得後再設定
Bitmap bmp = BitmapFactory.decodeResource(res,rid);
imageView.setImageBitmap(bmp );

但若用另一種方式
imageView.setImageResource(rid);

一樣會耗大量的記憶體處理
根據以下方式處理
http://givemepass.blogspot.tw/2011/11/blog-post_16.html

  1. 使用 BitmapFactory.decodeStream() 產生Bitmap
  2. 設定 BitmapFactory.Options inSampleSize,
         (inSampleSize值越大解析度越小,佔用memory也越小)
  3.  onPause/onStop/onDestory 時,將沒用到的Bitmap release(用recyle())


實作了之後,發現,記憶體初始佔量變小,
有20MB以上的差異效果。

可能在各種記憶體控管上(由其使用大圖)
需多注意,可能拉高記憶體,就容易發生之後的OutOfMemory問題。
可盡量的避免這樣的問題

其它參考網頁:
http://blog.xuite.net/ffc99a3b/ooxx/44391740-%5B%E8%BD%89%E8%BC%89%5D+Android+Out+Of+Memory(OOM)+%E7%9A%84%E8%A9%B3%E7%B4%B0%E7%A0%94%E7%A9%B6

------------
實作程式:
Bitmap bmp = getLocalBitmap(ctx,rid);

public Bitmap getLocalBitmap(Context ctx, int rid){
   InputStream inputStream = ctx.getResources().openRawResource(rid);
   return BitmapFactory.decodeStream(inputStream, null, getBitmapOptions(1));
}

public BitmapFactory.Options getBitmapOptions(int scale){
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inPurgeable = true;
   options.inInputShareable = true;
   options.inSampleSize = scale;
   return options;
}

---------------------------

也有其它OutOfMemory的錯誤訊息的顯示錯誤內容如下

Caused by: java.lang.OutOfMemoryError: Failed to allocate a 10240012 byte allocation with 9727265 free bytes and 9MB until OOM

java.lang.OutOfMemoryError: Failed to allocate a 4194316 byte allocation with 3346926 free bytes and 3MB until OOM

java.lang.OutOfMemoryError: (Heap Size=98304KB, Allocated=90289KB)







沒有留言:

張貼留言