如果先前从应用程序屏幕启动,则从主屏幕启动应用程序将在现有实例之上启动它,反之亦然

时间:2014-03-26 17:51:47

标签: android google-play

播放商店安装程序似乎存在某种错误,每当我尝试从主屏幕图标而不是应用程序屏幕恢复我的应用程序时,它将在我已运行的应用程序之上再次启动。

相反,这是正确的

我已尝试过此代码

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

但如果它尝试以我所述的方式启动,那么所有它都会使应用程序崩溃。

我的清单也设置为

android:launchMode="singleTask"

我发现如果我使用完全相同的APK并使用" adb install"安装它,我的应用程序正常工作并且正如我所料。

但是,如果我(或我的用户)下载apk并从下载安装它,我会发现上面描述的行为,即当用户导航到主页然后返回时,在堆栈上创建我的Activity的新实例通过发射器到应用程序。这可以通过" adb shell dumpsys活动"

进行验证

1 个答案:

答案 0 :(得分:0)

我在发布活动中使用以下内容修复了此问题

ublic class StartupActivity extends Activity {

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

    if (needStartApp()) {
        Intent i = new Intent(StartupActivity.this, GameActivity.class);
        startActivity(i);
    }

    finish();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    // this prevents StartupActivity recreation on Configuration changes 
    // (device orientation changes or hardware keyboard open/close).
    // just do nothing on these changes:
    super.onConfigurationChanged(null);
}

private boolean needStartApp() {
    final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    final List<RunningTaskInfo> tasksInfo = am.getRunningTasks(1024);

    if (!tasksInfo.isEmpty()) {
        final String ourAppPackageName = getPackageName();
        RunningTaskInfo taskInfo;
        final int size = tasksInfo.size();
        for (int i = 0; i < size; i++) {
            taskInfo = tasksInfo.get(i);
            if (ourAppPackageName.equals(taskInfo.baseActivity.getPackageName())) {
                // continue application start only if there is the only Activity in the task
                // (BTW in this case this is the StartupActivity)
                return taskInfo.numActivities == 1;
            }
        }
    } 

    return true;
}

}