【问题标题】:How to destroy all previous activities when I start activity from custom shortcut?当我从自定义快捷方式开始活动时,如何销毁所有以前的活动?
【发布时间】:2013-03-30 19:28:26
【问题描述】:

我的步骤:

  1. 启动器快捷方式启动 Activity A;
  2. 点击HOME按钮;
  3. 自定义快捷方式启动ActivityB;
  4. 点击BACK按钮 - 显示活动A

但是当我点击自定义快捷方式时,我希望我所有的旧活动关闭。我该怎么做?

清单:

activity A: android:launchMode="singleTop"
activity B: android:launchMode="singleTop" and android:exported="true"

java:

private void setShortCut() {
  Intent shortcutIntent = new Intent(getApplicationContext(), A.class);
  shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
  shortcutIntent.setAction(Intent.ACTION_MAIN);
  Intent intent = new Intent();
  intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
  intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "test");
  intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, ((BitmapDrawable)imgLogo.getDrawable()).getBitmap());
  intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
  sendBroadcast(intent);
}

【问题讨论】:

  • 你试过 android:noHistory="true" 吗?
  • launchMode="singleTop" 工作正常。您只有一个 ActivityA 实例和一个 ActivityB 实例。您无法使用singleTop 获得您想要的行为。
  • @Kgrover 如果我设置android:noHistory="true",那么每次ActivityA都会执行finish()方法。不仅是当我从自定义快捷方式启动我的应用程序时。
  • @David Wasser,你是绝对正确的。谢谢解释!!!您对销毁所有以前的活动有什么想法吗?
  • 你不想要 4. 单击 BACK 按钮 - 显示活动 A 对吗?

标签: android android-activity shortcut


【解决方案1】:
activity A: android:finishOnTaskLaunch="true"
activity B: android:finishOnTaskLaunch="true" and android:exported="true"  

来自http://developer.android.com/guide/topics/manifest/activity-element.html#finish的官方文档

“当用户再次启动其任务(在主屏幕上选择任务)时,是否应关闭(完成)活动的现有实例 - 如果应该关闭,则为“true”,“false” " 如果不是。默认值为 "false"。"

【讨论】:

  • 在这种情况下,单击 launcher-shortcut 我将始终看到 ActivityA。不仅在 custom-shortcut 点击之后。 我希望我的所有旧活动仅在 custom-shortcut start Activity B 之后关闭
【解决方案2】:

我建议您将自定义快捷方式也以ActivityA 开头,但在Intent 中传递一个额外的extra。在ActivityA.onNewIntent()ActivityA.onCreate() 中,您可以检查是否存在额外内容,如果存在,请启动ActivityB 并调用finish()。这应该会给你你想要的行为。

例如,在创建自定义快捷方式时添加:

shortcutIntent.putExtra("customShortcut", true);

并将此代码放入ActivityAonCreate()onNewIntent()

if (getIntent().hasExtra("customShortcut")) {
    Intent intent = new Intent(this, B.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity();
    finish();
    return;
}

【讨论】:

  • 现在我正在使用这种技术。但是用户总是在 ActivityB 启动时看到 ActivityA 秒。所以我想找到一种方法来关闭我所有的旧活动。
  • 好吧,如果 ActivityB 需要很长时间才能启动,那么关闭所有旧活动可能无济于事。如果您从根活动中删除 'launchMode="singleTop"` 并从启动意图中删除 Intent.FLAG_ACTIVITY_SINGLE_TOP,这将导致 ActivityA 在启动时重新创建。也许这会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多