Android 內存溢出問題分析。
Android雖然會自動管理內存,JAVA也有garbage collection (GC )內存回收機製。
但是如果程序在一次操作中打開幾個M的文件,那麼通常會出現下麵的錯誤信息。
02-04 21:46:08.703: ERROR/dalvikvm-heap(2429): 1920000-byte external allocation too large for this process.
或
02-04 21:52:28.463: ERROR/AndroidRuntime(2429): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
移動終端因為內存有限,往往圖片處理經常出現上述的錯誤。
解決方法:
1.明確調用System.gc();
這種內存回收會有一定的作用,但是請不要太期待。
2.圖片處理完成後回收內存。
請在調用BitMap進行圖片處理後進行內存回收。
bitmap.recycle();
這樣會把剛剛用過的圖片占用的內存釋放。
3.圖片處理時指定大小。
下麵這個方法處理幾個M的圖片時是必須的。
- BitMap getBitpMap(){
- ParcelFileDescriptor pfd;
- try{
- pfd = mCon.getContentResolver().openFileDescriptor(uri, "r");
- }catch (IOException ex){
- return null;
- }
- java.io.FileDescriptor fd = pfd.getFileDescriptor();
- BitmapFactory.Options options = new BitmapFactory.Options();
- //先指定原始大小
- options.inSampleSize = 1;
- //隻進行大小判斷
- options.inJustDecodeBounds = true;
- //調用此方法得到options得到圖片的大小
- BitmapFactory.decodeFileDescriptor(fd, null, options);
- //我們的目標是在800pixel的畫麵上顯示。
- //所以需要調用computeSampleSize得到圖片縮放的比例
- options.inSampleSize = computeSampleSize(options, 800);
- //OK,我們得到了縮放的比例,現在開始正式讀入BitMap數據
- options.inJustDecodeBounds = false;
- options.inDither = false;
- options.inPreferredConfig = Bitmap.Config.ARGB_8888;
- //根據options參數,減少所需要的內存
- Bitmap sourceBitmap = BitmapFactory.decodeFileDescriptor(fd, null, options);
- return sourceBitmap;
- }
- //這個函數會對圖片的大小進行判斷,並得到合適的縮放比例,比如2即1/2,3即1/3
- static int computeSampleSize(BitmapFactory.Options options, int target) {
- int w = options.outWidth;
- int h = options.outHeight;
- int candidateW = w / target;
- int candidateH = h / target;
- int candidate = Math.max(candidateW, candidateH);
- if (candidate == 0)
- return 1;
- if (candidate > 1) {
- if ((w > target) && (w / candidate) < target)
- candidate -= 1;
- }
- if (candidate > 1) {
- if ((h > target) && (h / candidate) < target)
- candidate -= 1;
- }
- if (VERBOSE)
- Log.v(TAG, "for w/h " + w + "/" + h + " returning " + candidate + "(" + (w/candidate) + " / " + (h/candidate));
- return candidate;
- }
最後更新:2017-04-02 06:51:43
上一篇:
ViewFlipper用法
下一篇:
C# 計算中文漢字筆畫數
“新SaaS”引爆產業奇點《2017中國SaaS用戶研究報告》
strcmp
android 中關於 activity 的一些理解
PostgreSQL 線性回歸 - 股價預測 1
淺談各種基於物聯網的商業模式
用戶 'sa' 登錄失敗。原因: 該帳戶被禁用。 (Microsoft SQL Server,錯誤: 18470)
Sql Server 2008 R2 激活密鑰
The Future of Augmented Reality and Virtual Reality
android 中係統自帶的主題與樣式(theme and style)
Universal Image Loader for Android 使用實例