Catching OutOfMemoryError in decoding Bitmap

前端 未结 4 894
天命终不由人
天命终不由人 2020-12-13 14:30

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 pract

4条回答
  •  没有蜡笔的小新
    2020-12-13 14:57

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

提交回复
热议问题