I have an app which goes to background when the user press the back button-
@Override
public void onBackPressed() {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
So the only way the user will shutdown the app is by using the task manager
and manually stop it.
Now, I'm trying to test my onDestroy
by closing my app using the task manager
in my Android device, yet, on Android Studio
the app seem to be still alive, it says Session: '<app_name>' : running
and onDestroy
is not called.
Why is that and how can I fix it?
**I want to see that onDestroy
is called when I'm stopping my app using the task manager
and by manually stopping it, as the user will have to do if he wants to shut my app down, Not by pressing back button. by pressing back button the app will be alive and its fine, it's what I want.
Why relaunch the activity on back pressed? Just do nothing.
@Override
public void onBackPressed() {
}
Call finish()
to destroy an Activity.
@Override
public void onBackPressed() {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
finish();
}
Under Settings → Developer Options , go to the Apps section and enable " Don't keep activities " option. Then every time you hit the back button the App will be destroyed. I you want to override the Back Button action to destroy app you could override onKeyDown in your Activity
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
}
return super.onKeyDown(keyCode, event);
}
You can either call finish();
, for ex, after startActivity(setIntent);
Or, you can call super.onBackPressed();
, also at the end.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.