Android: Preventing going back to the previous activity

I want to do this on Android: basically when BACK button is pressed on the phone, I want to prevent a specific activity to return to its previous one.

Specifically, I have login and sign up screens, both start a new activity called HomeScreen when successful login/signup occurs. Once HomeScreen is started, I want to prevent the users to be able to return login or sign up screens with pressing BACK key.

I tried using Intent.FLAG_ACTIVITY_NO_HISTORY but since the application has Facebook integration, when the 'Login with Facebook' is used, Facebook should return to initial login screen, therefore I should keep a history of these activities.

I thought of overriding behaviour of BACK button on HomeScreen to directly finish application when the button is pressed and I used

@Override
public void onBackPressed() {
    finish();
}

but that also does not work.

I am quite new in Android development, so any help would be very useful.

Thanks in advance.


My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity , call finish() . When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.


Following solution can be pretty useful in the usual login / main activity scenario or implementing a blocking screen.

To minimize the app rather than going back to previous activity, you can override onBackPressed() like this:

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

moveTaskToBack(boolean nonRoot) leaves your back stack as it is, just puts your task (all activities) in background. Same as if user pressed Home button .

Parameter boolean nonRoot - If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.


I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.

Here are a few links that might help:

Disable back button in android

  MyActivity.java =>
    @Override
    public void onBackPressed() {

       return;
    }

How can I disable 'go back' to some activity?

  AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>
链接地址: http://www.djcxy.com/p/26166.html

上一篇: 在android中检测主页按钮

下一篇: Android:防止回到以前的活动