Catching OutOfMemoryError in decoding Bitmap

前端 未结 4 865
天命终不由人
天命终不由人 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 15:05

    Though it might not be a good idea to catch OutOfMemoryError using try-catch. But, sometimes you have no choice, because all of us hate app crashes. So, what you can do is

    1. Catch OutOfMemoryError using try-catch
    2. Since, after this error your activity may become unstable, restart it.
    3. You may disable animations so that user doesn't know that activity is restarted.
    4. You may put some extra data in intent to know that app was crashed during previous run.

    How I did is:

        try {
            //code that causes OutOfMemoryError
        } catch (Exception e) {
            // in case of exception handle it
            e.printStackTrace();
        } catch (OutOfMemoryError oome)
        {
            //restart this activity
            Intent i=this.getIntent();
            i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); //disable animation
    
            //EXTRA_ABNORMAL_SHUTDOWN is user defined       
            i.putExtra(this.EXTRA_ABNORMAL_SHUTDOWN, true);
            //put extra data into intent if you like
    
            finish(); //and finish the activity
            overridePendingTransition(0, 0);
            startActivity(i); //then start it(there is also restart method in newer API)
            return false;
        }
    

    And then on onCreate of Activity you can resume(something like this):

    boolean abnormalShutdown=getIntent().getBooleanExtra(this.EXTRA_ABNORMAL_SHUTDOWN, false);
    if (abnormalShutdown)
    {
        //Alert user for any error
        //get any extra data you put befor restarting.
    }
    

    This approach saved my app. Hope it helps you too!!

提交回复
热议问题