如何避免在最近的卡片中出现多个应用程序实例?

How to avoid multiple instance of app in recent cards?

我的应用实例数量有些问题。在某些情况下,我的应用程序在最近的卡片列表中有不止一个实例。

案例一

Noramlly 打开应用程序。 Action main 是 SplashScreen.class > MainActivity.class > Fragment(view)。在这种情况下,应用程序在最近的卡片中只有一个实例。

案例二

应用程序已打开,然后可以通过邮箱打开应用程序,特别是来自gmail,电子邮件包含可以打开我的应用程序的附件。流向这种情况 SharedData.class > MainActivity.class > Fragment(view)。现在我有两个应用实例。

我想要的是关闭上一个实例并首先启动新的或打开的附件。

测试了文档 App manifest file - activity 中 activity 的一些参数。结果不满意,专门测试了lunchmode(“singleTop”,“singleTask”和“singleInstance”)。关闭一个是“singleTask”,关闭前一个实例,但必须点击两次附件才能打开新实例(实例存在>点击附件>第一个实例关闭(不存在任何实例)>点击附件>打开新实例)。

如果有人建议如何解决这个问题,我将不胜感激。这个问题存在于堆栈上的许多组合中,但 none 处理它。

发生这种情况是因为您只是添加片段而没有检查片段是否已经可用。所以在添加片段之前先检查一下。

 public void replaceFragment(Fragment newFragment, String tag)
 {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    if (manager.findFragmentByTag(tag) == null) {
        ft.replace(R.id.container_fragment, newFragment, tag)
                .addToBackStack(tag).commit();
    }else {
        ft.show(manager.findFragmentByTag(tag)).commit();
    }
 }

如果想了解更多关于该片段的信息,请看一看here and go through the official documentation

我稍后搜索并找到解决方案:

上的 AndroidManifest 中设置 android:launchMode="singleTask"
<activity
    android:launchMode="singleTask"
    android:name=".MainActivity">
</activity>

然后在SharedData.class设置

private void startMainActivityAndFinishCurrent() {
    Intent intent = new Intent(ContextInstance.getContext(), MainActivity.class);
    startActivity(intent);
    finish();
}

就是这样,但最有趣的是理解清单中的 activity 标签