gpt4 book ai didi

android - 在解码位图时捕获 OutOfMemoryError

转载 作者:IT老高 更新时间:2023-10-28 22:20:46 27 4
gpt4 key购买 nike

即使您尝试了一些减少内存使用的方法,捕捉 OutOfMemoryError 是否也是一种好习惯?还是我们不应该捕获异常?哪一个更好?

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()后大概率会起作用。

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.
}
}

关于android - 在解码位图时捕获 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7138645/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com