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

Wau*_*ugh 7 android

这是我的问题 -

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

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

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

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

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

Ste*_*viN 9

@Palejandro,你在这里.将下面的代码放入主活动 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在我的项目中使用了这段代码,它运行正常!


col*_*red 8

我相信你需要投入

<activity
    android:launchMode="singleInstance"
</activity>
Run Code Online (Sandbox Code Playgroud)

在清单文件中.


小智 1

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

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