如何清除 Android Stack 的活动?

How to clear the Android Stack of activities?(如何清除 Android Stack 的活动?)

本文介绍了如何清除 Android Stack 的活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Android 中有一个包含多个活动的应用程序,我希望用户能够通过按菜单按钮退出.我的问题是

I have an application with several Activities in Android and I want the user to be able to log-out by pressing a menu button. The problem I have is that

A) Android 不允许您终止应用程序并且
B) 即使当我再次将用户发送到 LoginActivity 时,他们也可以随时按 back 并立即回到他们所在的上一个活动.

A) Android doesn't let you terminate the application and
B) even when I send the user to the LoginActivity again they can always press back and get right back to the previous activity they were in.

我已经尝试使用以下两个标志启动 Activity:

I already tried to launch the Activity with the two following flags:

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

我也自己尝试过.

我还尝试在 startActivity(intent) 之后调用 finish(),因为我在另一个 StackOverflow 中阅读问题.

I also tried calling finish() after startActivity(intent) as I read in another StackOverflow question.

推荐答案

在您的登录活动中,覆盖后退按钮,因此它会隐藏您的应用而不是完成活动:

In your login activity, override the back button, so it hides your app instead of finishing the activity:

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

还要确保在根活动上设置 android:alwaysRetainTaskState="true",这样 Android 不会在用户不活动 30 分钟后清除您的堆栈(包括登录活动).

Also be sure to set android:alwaysRetainTaskState="true" on the root activity, so Android doesn't clear your stack (including the login activity) after 30min of inactivity from user.

然后在登录成功时调用finish().

Then just call finish() when there is a successful login.

这篇关于如何清除 Android Stack 的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何清除 Android Stack 的活动?

基础教程推荐