Reputation: 11
Hi, I need run some line of code after an activity closes but not when a new intent is started. How can I do that? I have tried onStop()
, onPause()
and onDestory()
but all these also run the code when a start a new intent. I only want the code to run when the back button is pressed or the app is closed. Any suggestions?
Upvotes: 1
Views: 112
Reputation: 161
If you want to catch the back button, than add this to your activity (API):
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your code
return true;
}
return super.onKeyDown(keyCode, event);
}
Since API level 5 you can also use onBackPressed().
If your activity is going to the background by other reasons, than onPause() should be called. You can check if the instance is killed, e.g. by the task manager, by calling isFinishing(). If it comes to the foreground again, onResume() is called.
Upvotes: 2
Reputation: 13541
You can override the onBackpressed() method as provided by Activity to achieve what you want.
Upvotes: 0
Reputation: 444
For back button, you could override onBackPressed
.
If you want to know whether you app is being closed in onDestroy
you could check with this.isFinishing()
(returns a boolean).
Upvotes: 0