问题
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 open the app again, it will direct them to login activity and not start again from register. However, when I press back button from login activity it still take me back to register activity which could change the already saved SharedPreferences. I wanna disable this function, how to simply exit the app when user press the back button?
Thanks,
回答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.
<activity
android:name=".RegistrationActivity"
...
android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
回答2:
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
This method catches when the Back Button is pushed.
回答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:
public void finish ()
.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:
public void finishActivity (int requestCode)
.Force finish another activity that you had previously started with startActivityForResult(Intent, int).
回答4:
Alternatively to Paul-Jan's answer, you could simply call finish() right after you call startActivity(...) in your register activity.
来源:https://stackoverflow.com/questions/12695199/android-how-to-exit-activity-when-back-button-is-pressed