在解码位图时捕获 OutOfMemoryError [英] Catching OutOfMemoryError in decoding Bitmap
本文介绍了在解码位图时捕获 OutOfMemoryError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
即使您已经尝试了一些减少内存使用的方法,捕获 OutOfMemoryError 是否是一个好习惯?或者我们应该只是不捕捉异常?哪种做法更好?
Is it a good practice to catch OutOfMemoryError even you have tried some ways to reduce memory usage? Or should we just not catching the exception? Which one is better practice?
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(file, options);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
谢谢
推荐答案
捕捉它一次然后再给 decodeFile
一次机会是一个好习惯.抓住它并调用 System.gc()
并再次尝试解码.调用System.gc()
后很有可能会起作用.
It's good practice to catch it once and give decodeFile
another chance. Catch it and call System.gc()
and try decoding again. There is a high probability that it will work after calling System.gc()
.
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(file, options);
} catch (OutOfMemoryError e) {
e.printStackTrace();
System.gc();
try {
bitmap = BitmapFactory.decodeFile(file);
} catch (OutOfMemoryError e2) {
e2.printStackTrace();
// handle gracefully.
}
}
这篇关于在解码位图时捕获 OutOfMemoryError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文