Reputation: 635
In my application i want to exit the application when clicking the back button.When first time entered into the app when clicking back from this screen means it is exiting.But if i got to next screen and coming back to this screen and clicking back means going to previous screen not exiting.Thanks in advance..
My code:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
finish();
java.lang.System.exit(0);
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 0
Views: 384
Reputation: 1506
You should use :
if (keyCode == KeyEvent.KEYCODE_BACK) { finishAffinity(); }
Upvotes: 0
Reputation: 5116
call moveTaskToBack(true) on your Activity (it doesn't kill your app but remove it from screen)
Upvotes: 0
Reputation: 9330
one better way to do that is by starting second activity using
startActivityForResult();
then, when the user click back button check the result by overriding
onActivityResult(){}
and finish the first activity too.
Upvotes: 0
Reputation: 3538
If you want the back button to always exit the app if pressed from the launcher activity, you can use the following to make it a singletask so that app will exit with back press.
In android manifest file: android:launchMode="singleTask"
While directing to this activity using startActivity(), intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Upvotes: 0
Reputation: 2573
I would advice against implementing such functionality. The back button works the same way in most applications and users feel safe knowing that the back button eventually always puts them back to home screen. Maybe a TabView could be a better way of switching between the two activities?
Upvotes: 1