【问题标题】:How to close all activities and exit from an app如何关闭所有活动并退出应用程序
【发布时间】:2016-07-14 12:32:17
【问题描述】:

我的应用旨在只允许登录用户访问活动。如果用户注销,则共享首选项布尔 isLogged 设置为 false,并且用户不应访问除 LoginActivity 之外的其余活动。

但是,我可以通过按后退按钮访问所有以前打开的活动。

我会在打开每个活动时使用finish();,但我希望用户在登录时仍然使用后退按钮。

我已经尝试过其他类似问题的解决方案,例如

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

并在我的 LoginActivity 的 onCreate() 上添加了

if (getIntent().getBooleanExtra("EXIT", false)) {
         finish();
    }

当我按下注销选项时,会打开上一个活动。

有什么建议可以帮帮我吗?

【问题讨论】:

标签: android android-intent


【解决方案1】:

你应该使用这个标志,清除你的任务并创建一个新的

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

【讨论】:

    【解决方案2】:

    试试这个

    您需要在 Intent 中添加这些标志..

    Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("EXIT", true);
    startActivity(intent);
    finish();
    

    【讨论】:

      【解决方案3】:
      if (getIntent().getBooleanExtra("EXIT", false)) {
              finish();
      android.os.Process.killProcess(android.os.Process.myPid());
          }
      

      【讨论】:

        【解决方案4】:

        尝试在数组中添加所有活动,当您想要删除时,只需将其从数组中删除并完成该活动。在这里查看我的答案Remove activity from stack

        【讨论】:

          【解决方案5】:

          我也遇到过类似的情况。正如我所知道的,即使我一开始调用finish() 函数,整个onCreate() 函数也会被执行。然后它将完成。在我的场景中,在onCreate() 函数中,我调用了另一个活动。所以即使主要活动在onCreate() 之后完成,第二个活动仍然存在。所以我的解决方案是,

          private boolean finish = false;

          在主函数的onCreate()中,

          if(intent.getBooleanExtra("EXIT", false)) {
                  finish();
                  finish = true;
              }
          

          我检查了所有导航

          if(!finish) {
                  Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                  startActivity(intent);
                  finish();
              }
          

          我的退出函数是,

          Intent intent = new Intent(getApplicationContext(), MainActivity.class);
              intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
              intent.putExtra("EXIT", true);
              startActivity(intent);
          

          【讨论】:

            【解决方案6】:

            要在按下后退按钮时退出应用程序,请尝试使用以下代码:

            finishAffinity();
            

            【讨论】:

            • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
            猜你喜欢
            • 2018-01-23
            • 1970-01-01
            • 2013-12-11
            • 1970-01-01
            • 1970-01-01
            • 2022-01-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多