Release Memory of Particular Activity when it is Destroyed

前端 未结 7 1545
说谎
说谎 2020-12-15 05:38

I have a launcher Activity that load and resize big bitmap as it\'s background when it opens.

Whenever hit the back button, the Activity is

相关标签:
7条回答
  • 2020-12-15 06:00

    try to finish the activity when pressing back button

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
    
    0 讨论(0)
  • 2020-12-15 06:07

    Add following code for it

    @Override
    protected void onDestroy() {
        //android.os.Process.killProcess(android.os.Process.myPid());
    
        super.onDestroy();
        if(scaledBitmap!=null)
                {
                    scaledBitmap.recycle();
                    scaledBitmap=null;
                }
    
         }
    
    0 讨论(0)
  • 2020-12-15 06:07

    Finishing an Activity doesn't clear its memory. It only removes the Activity from its stack, Android will clear its memory when it needs memory (garbage collection),if you face memory issue from drawable,

    • Reducing the drawable size may solve your problem.
    • Insufficient memory in Android devices also leads to memory issues.
    0 讨论(0)
  • 2020-12-15 06:10

    even after destroying the activity by calling finish(), it's resources are queued for garbage collection. activity will be freed during next GC cycle.

    @Override
    public void onDestroy() {
        super.onDestroy();
        Runtime.getRuntime().gc();      
    }
    

    You can also use android:largeHeap="true" to request a larger heap size, in your application tag in manifest.

    0 讨论(0)
  • 2020-12-15 06:15

    add this to your code

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
  • 2020-12-15 06:16

    Try to set the bitmap to null while activity is destroyed and if desire run the garbage collector.

    0 讨论(0)
提交回复
热议问题