Release Memory of Particular Activity when it is Destroyed

跟風遠走 提交于 2019-11-28 23:11: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;
            }

     }

In activity if you're calling the finish() method from is destroyed and all its resources are queued for garbage collection.

So, all memory that was used by this activity will be freed during next GC cycle.

OR

you can try this to clean memory,

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

check this details. hope that helps.

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

add this to your code

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
        finish();
    }
    return super.onKeyDown(keyCode, event);
}

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.

try to finish the activity when pressing back button

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}
Anbarasu Chinna

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!