我的 Android 应用程序的两个实例正在运行....如何避免这种情况?

问题描述 投票:0回答:7

这是我的问题 -

  1. 我将 .apk 文件复制到手机存储卡上,然后单击它启动我的应用程序,它允许我安装我的应用程序。我安装我的应用程序。最后,我弹出系统安装窗口,其中包含两个选项“打开”和“完成” “。当我单击“打开”时,我的应用程序启动了。到目前为止,一切正常,没有任何问题。

  2. 现在在我的应用程序中,我单击一个按钮,结果正在进行一些下载(显示进度对话框)。现在我按主页按钮,所以我的应用程序转到后台。

  3. 现在,我再次通过进入菜单并单击我的应用程序图标来启动我的应用程序。

  4. 预期结果 - 我仍然应该看到下载进度对话框。 实际结果 - 我的应用程序的新实例/会话正在启动。

那么如何避免这种情况,以便我的应用程序只运行一个和一个实例/会话。

android
7个回答
10
投票

@Palejandro,你在这里。将以下代码放入您的 main Activity

onCreate()
方法中:

// Possible work around for market launches. See
// http://code.google.com/p/android/issues/detail?id=2373
// 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();
    final String intentAction = intent.getAction();
    if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
        Log.w(TAG, "Main Activity is not the root. Finishing Main Activity instead of launching.");
        finish();
        return;
    }
}

我在我的项目中使用了这段代码,它工作得很好!


8
投票

我相信你需要放

<activity
    android:launchMode="singleInstance"
</activity>

在清单文件中。


1
投票

你的

OnPause
OnResume
OnCreate
做什么? 我敢打赌,您不会在 OnPause 中保存任何内容,并且始终通过 OnCreate 启动一个新实例。

您应该阅读有关活动生命周期的注释。


0
投票

如果你还没有解决这个问题,我会说当按下 home 时你的应用程序实际上被杀死了,或者你可能有一个错误,无法锁定任何保持状态的对象。


0
投票

// 在调用 super 和 setcontentview() 之前将以下代码放入启动器活动中

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);

    // get the info from the currently running task
    List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(10);
    boolean alreadyTask=false;
    for(ActivityManager.RunningTaskInfo info : taskInfo){
        ComponentName componentInfo = info.topActivity;
        String value= componentInfo.getPackageName();
        if(value.contains(getPackageName()) && !info.topActivity.getClassName().contains(getPackageName()+".LauncherActivity")){
            alreadyTask=true;
            Log.i(TAG, "second instance found!!!");
            break;
        }
    }

    if(alreadyTask){
        finish();
    }

0
投票

我没有解决方案,但问题是,与从主屏幕打开应用程序相比,直接从安装打开应用程序时用于启动应用程序的意图是不同的。由于它将由两个不同的意图启动,因此它将在第二次打开一个新实例。

一个快速解决方法是在安装应用程序后避免按“打开”。按“完成”,然后自己找到该应用程序。

请参阅:http://code.google.com/p/android/issues/detail?id=2373


0
投票

我已将其放入 AndroidManifest.xml 中

    <activity
     ...
    android:launchMode="singleInstance"
    ...
    </activity>
© www.soinside.com 2019 - 2024. All rights reserved.