我的应用程序有以下流程屏幕:

主屏->屏1->屏2->屏3->屏4->屏5

现在我在每个屏幕上都有一个公共注销按钮

(主屏/ 1屏/ 2屏/ 3屏/ 4屏/ 5屏)

我想当用户点击注销按钮(从任何屏幕),所有屏幕将完成,一个新的屏幕登录将打开。

我已经尝试了几乎所有的FLAG_ACTIVITY来实现这一点。 我还通过一些答案在stackoverflow,但不能解决这个问题。 我的应用程序是在Android 1.6上,所以不能使用FLAG_ACTIVITY_CLEAR_TASK

有什么办法解决这个问题吗?


当前回答

最好的方法关闭所有以前的活动,并清除内存

finishAffinity()
System.exit(0);

其他回答

我想我迟到了,但有一个简单而简短的答案。Activity中有一个finishAffinity()方法,它将完成当前活动和所有父活动,但它只能在Android 4.1或更高版本中工作。

对于API 16+,使用

finishAffinity ();

16岁以下使用

ActivityCompat.finishAffinity (YourActivity.this);

希望能有所帮助!

shareedit 回答时间是18年5月27日8:03

阿卡什Taru

我为此实现了一个解决方案(我想我在Stack Overflow的某个地方找到了它,但我不记得了,所以感谢在第一个地方做这件事的人):

在你的任何活动中都这样做:

// Clear your session, remove preferences, etc.
Intent intent  = new Intent(getBaseContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

然后在你的LoginActivity,覆盖onKeyDown:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

在启动你的新活动之前,只需添加以下代码:

finishAffinity();

或者如果你想让它在以前的Android版本中工作:

ActivityCompat.finishAffinity(this);

我找到了这条路,它会清除所有历史并退出

Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
Intent intent = new Intent(getApplicationContext(), SplashScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

finish();
System.exit(0);

从developer.android.com:

public void finishAffinity () 在API级别16中添加

Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.

请注意,此结束不允许您向前一个活动交付结果,如果您试图这样做,则会抛出异常。