其他分享
首页 > 其他分享> > android – 如何在使用不同的Intent启动时阻止Activity的多个实例

android – 如何在使用不同的Intent启动时阻止Activity的多个实例

作者:互联网

当我使用Google Play商店应用程序(以前称为Android Market)上的“打开”按钮启动时,我在应用程序中遇到了一个错误.似乎从Play商店启动它使用不同的Intent,而不是从手机的图标应用程序菜单中启动它.这导致启动相同活动的多个副本,这些副本彼此冲突.

例如,如果我的应用程序包含活动A-B-C,则此问题可能会导致堆栈A-B-C-A.

我尝试在所有活动上使用android:launchMode =“singleTask”来解决这个问题,但每当我按下HOME按钮时,它都会产生不必要的副作用,即将活动堆栈清除为root.

预期的行为是:A-B-C – >首页 – >当应用程序恢复时,我需要:A-B-C – >首页 – > A-B-C

是否有一种很好的方法可以防止启动相同类型的多个活动,而无需在使用HOME按钮时重置为根活动?

解决方法:

将此添加到onCreate,你应该很高兴:

// Possible work around for market launches. See https://issuetracker.google.com/issues/36907463
// for more details. Essentially, the market launches the main activity on top of other activities.
// we never want this to happen. Instead, we check if we are the root and if not, we finish.
if (!isTaskRoot()) {
    final Intent intent = getIntent();
    if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(intent.getAction())) {
        Log.w(LOG_TAG, "Main Activity is not the root.  Finishing Main Activity instead of launching.");
        finish();
        return;       
    }
}

标签:back-stack,activity-stack,android,google-play
来源: https://codeday.me/bug/20190915/1805702.html