android - 在从服务开始 Activity 之前关闭所有 Activity

标签 android android-intent

我已经在我的应用程序中实现了 GCM,并且根据从服务器接收到的有效负载,我正在启动一个名为 Activity(B) 的 Activity 。

我的要求是,如果我在使用该应用程序时从服务器接收到该特定有效负载,并且假设我在 Activity (A) 上,那么它 (A) 应该关闭并且只有 Activity(B) 应该在该应用程序的实例中一旦 Activity B 从我的 GCM 的 GCMIntentService 类开始,所有堆叠的 Activity 都应该关闭。

我尝试过但没有奏效的事情。

Intent myIntent=new Intent(myContext,ActivityB.class);
myIntent.setFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myContext.startActivity(myIntent);

我也试过flag

Intent.FLAG_ACTIVITY_NEW_TASK

所有组合。

但运气不好。如果我在声明 Activity 时可能在 list 中的某处出错,请告诉我我没有使用任何特殊参数,如 launchMode 或我的 list 文件中的其他参数。

最佳答案

您需要使用以下代码启动应用程序的根 Activity(即: list 中具有 ACTION=MAINCATEGORY=LAUNCHER 的 Activity) :

Intent intent = new Intent(context, RootActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("launchActivityB", true);

这将从任何现有任务中清除所有 Activity 并启动 RootActivity 的新实例。在 RootActivity.onCreate() 中添加以下代码(在调用 super.onCreate() 之后):

if (getIntent().hasExtra("launchActivityB")) {
    // We have been started so that we can launch ActivityB, finish and do that now
    finish(); // End this activity right now
    Intent intent = new Intent(this, ActivityB.class);
    startActivity(intent);
    return; // do no further processing in this activity
}

注意:尝试使用 FLAG_ACTIVITY_CLEAR_TOP 启动 ActivityB 没有达到您想要的效果是因为 FLAG_ACTIVITY_CLEAR_TOP 的工作方式。它清除现有任务中的所有 Activity 位于您尝试启动的 Activity 的现有实例之上(之前)(在本例中为 ActivityB) .由于您的任务中没有 ActivityB 的现有实例,因此该标志没有执行任何操作。

关于android - 在从服务开始 Activity 之前关闭所有 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17178450/

相关文章:

php - DataBuffer JSON 的内部数据泄漏

android - RecyclerView 与 GridLayoutManager 插入项目错误位置

android - Google 游戏登录状态未在之前的 Activity 中共享

java - 为什么通知不显示在 API 28 中?

java - 如何使用Java检查android中的editText框是否为空

android - 了解 ACTION_MAIN

android - 在后台线程中修改适配器

android - 安装没有成功

android - 测试 Android IAB - 订阅已取消但购买状态仍然有效

Android Intent 启动适当的聊天客户端