1

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,

Community
  • 1
  • 1
Hendra Anggrian
  • 5,780
  • 13
  • 57
  • 97

4 Answers4

9

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>
Sam
  • 86,580
  • 20
  • 181
  • 179
Paul-Jan
  • 16,746
  • 1
  • 63
  • 95
1
@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
}

This method catches when the Back Button is pushed.

Sam
  • 86,580
  • 20
  • 181
  • 179
Md Abdul Gafur
  • 6,213
  • 2
  • 27
  • 37
  • This intercepts the back button click, but how does it prevent the user from returning to the previous Activity? – Sam Oct 02 '12 at 17:33
  • Use this , it help you to go previous activity, mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(mainIntent); finish(); – Md Abdul Gafur Oct 02 '12 at 17:37
0
@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).

Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
0

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

dennisdrew
  • 4,399
  • 1
  • 25
  • 25