Skip to content Skip to sidebar Skip to footer

Android - How To Exit Activity When Back Button Is Pressed?

Possible Duplicate: android pressing back button should exit the app I'm building a register and login screen just for an exercise. So I put SharedPreferences so that when user

Solution 1:

If you never want the back button to return to the registration screen, the cleanest solution would be to exclude it from the activity history using the noHistory attribute in the manifest, i.e.

<activityandroid:name=".RegistrationActivity"...android:noHistory="true" ><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity>

Solution 2:

@OverridepublicvoidonBackPressed() {
    // TODO Auto-generated method stubsuper.onBackPressed();
}

This method catches when the Back Button is pushed.

Solution 3:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
   if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() ==KeyEvent.ACTION_DOWN)
     {
        //Handler for KEYCODE_BACK Pressing.
     }
}

If you want to close the activity:

publicvoidfinish ()

.Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

If you want to close another activity started via startActivityForResult:

publicvoidfinishActivity(int requestCode)

.Force finish another activity that you had previously started with startActivityForResult(Intent, int).

Solution 4:

Alternatively to Paul-Jan's answer, you could simply call finish() right after you call startActivity(...) in your register activity.

Post a Comment for "Android - How To Exit Activity When Back Button Is Pressed?"