在解码位图捕捉的OutOfMemoryError位图、OutOfMemoryError

2023-09-05 06:48:04 作者:糾纏菂宿掵

它是一个很好的做法,以赶上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();
}

感谢

推荐答案

它很好的做法,一旦抓住它,并给德codeFILE 一次机会。抓住它,并调用的System.gc()并重新解码。有一个高的概率,它会调用工作后的System.gc()

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