Android: 如果应用程序从另一个应用程序打开,则launchMode singleTop无法工作

5

我有一个应用程序,如果从另一个应用程序启动(例如通过Play商店),它会出现异常行为。它不会恢复到已存在的Activity,而是作为新实例重新启动。

我的解决方案:

  • manifest.xml中使用launchMode="singleTop"声明每个活动
  • 我尝试使用launchMode=singleTask,但其具有相同的行为
  • 在每个启动新ActivityIntent上使用附加的intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
  • onNewIntent()未在已运行的实例中调用

我使用以下代码从另一个应用程序(带和不带额外的addFlag())启动我的应用程序:

Intent launchIntent = getPackageManager().getLaunchIntentForPackage("my.package.name");
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(launchIntent);

我的启动活动是一个SplashScreenActivity,如果用户已登录,则使用以下代码启动MainActivity并完成finished()

 Intent intent = null;
 intent = new Intent(SplashScreenActivity.this, HomeActivity.class);
 intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
 startActivity(intent);
 finish();

我有什么遗漏吗?欢迎任何建议!
2个回答

6

在进一步研究后,我在SplashScreenAvtivity:onCreate()中添加了以下代码。

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!isTaskRoot())
    {
        String intentAction = getIntent().getAction();
        if (getIntent().hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
            finish();
            return;
        }
    }
    //...

如果应用已经在运行,这将关闭 SplashScreenActivity。它适用于所有 launch-modes


3
请尝试在SplashScreenActivity中使用singleTask而不是singleTop。 根据http://developer.android.com/guide/topics/manifest/activity-element.html#lmode,“系统会在新任务的根处创建该活动,并将意图路由到它。但是,如果该活动的实例已经存在,则系统通过调用其onNewIntent()方法将意图路由到现有实例,而不是创建一个新实例。”

我忘了承认,我已经尝试过launchMode=singleTasksingleInstance,但是行为仍然保持不变..... - longi
singleTask 是危险的,因为它会清除所有在其上方的活动。 - thecr0w

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接