如何清除Android活动堆栈? [英] How to clear the Android Stack of activities?

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

问题描述

我在 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.

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

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);

我也亲自尝试过.

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

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);
}

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

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活动堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆