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

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

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

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

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

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

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


当前回答

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

finishAffinity();

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

ActivityCompat.finishAffinity(this);

其他回答

顺便说一句,很高兴知道 这个答案有效(https://stackoverflow.com/a/13468685/7034327)

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();

然而这行不通

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

. setflags()会替换之前的任何标志,不会追加任何新标志,而. addflags()会。

所以这个也可以

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

当用户点击登出按钮,然后写以下代码:

Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

并且登录后如果调用new activity,不要使用finish();

我试了我这边的旗子,还是没用。我有一个设计非常相似的应用程序,我有一个可能的解决方案在逻辑方面。我已经使用共享首选项构建了登录和注销。

如果我登出,数据在我的共享首选项被销毁/删除。

从我的任何活动(如Home.java)中,我检查共享首选项是否有数据,在这种情况下,它不会有数据,因为我从其中一个屏幕注销时销毁了它。因此,逻辑破坏/完成该活动,并将我带回Login活动。您可以在所有其他活动中复制此逻辑。

但是,请记住在onPostResume()中执行这个检查,因为这是当你返回Home.java时调用的

代码示例如下:

@Override
protected void onPostResume() {
    SharedPreferences pref = this.getSharedPreferences("user_details", Context.MODE_PRIVATE);
    if (pref.getAll().isEmpty()){
        //Shared Preferences has no data.
        //The data has been deleted
        Intent intent = new Intent(getApplicationContext(), Login.class);
        startActivity(intent);
        finish();
        //Finish destroys that activity which in our case is the Home.java
    }


    super.onPostResume();
}

简单地说,当您从登录屏幕离开时,而不是在完成登录屏幕时。

然后在所有转发活动中,使用这个来登出:

final Intent intent = new Intent(getBaseContext(), LoginScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);

它工作得很完美。

从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.

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