【问题标题】:How do you avoid more than one instance of an Activity when created from widget?从小部件创建时,如何避免多个 Activity 实例?
【发布时间】:2014-08-17 01:03:36
【问题描述】:

我想在我的小部件中按下按钮时启动我的应用程序\活动。

我正在使用此代码:

    Intent launchApp = context.getPackageManager()


        Intent launchApp = context.getPackageManager()
                .getLaunchIntentForPackage("com.sexy.code");
        launchApp.setData(Uri.parse(listItemClickIntent
                .toUri(Intent.URI_INTENT_SCHEME)));
        pIntent = PendingIntent.getActivity(context, 0, launchApp,
                PendingIntent.FLAG_UPDATE_CURRENT);

我的问题是在我的应用程序已经在后台运行的情况下,所以一切看起来都很好,直到我关闭那个打开的活动并在它后面发现另一个活动。这就像我需要退出应用程序两次。

如何避免这种情况?

【问题讨论】:

  • 请阅读 android manifest 启动模式文档以了解活动
  • @Jesus Dimrix 启动模式不是最佳实践

标签: android android-activity android-widget instance


【解决方案1】:

试试这个:

launchApp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

来自FLAG_ACTIVITY_CLEAR_TOP 的文档:

如果设置了,并且正在启动的 Activity 已经在当前任务中运行,那么不会启动该 Activity 的新实例,而是关闭它之上的所有其他 Activity,并且此 Intent 将被传递到(现在在顶部)作为新 Intent 的旧活动。

这个标志也可以和FLAG_ACTIVITY_NEW_TASK结合,如:

launchApp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                   Intent.FLAG_ACTIVITY_NEW_TASK);

您也可以单独使用它们,具体取决于您想要的行为。

【讨论】:

  • Nickolai Astashonok 的回答效果很好,有什么理由改用你的方式吗?
  • FLAG_ACTIVITY_NEW_TASK 的工作方式与 launchMode=singleTask 相同。如果您想在代码或 XML 中执行此操作,这只是一个偏好问题。
【解决方案2】:

如何使用启动模式标志:

android:launchMode="singleTask"

您的活动应如下所示:

 <activity
            android:name=".YourActivity"
            android:launchMode="singleTask"
            android:configChanges="orientation|screenSize" >

【讨论】:

  • 这不是最佳实践,在创建片段时每个人都有这个问题,原因是 saveInstanceState 在旋转移动设备时它会一次又一次地创建实例,每次你想检查 savedInstanceState != null 与否
猜你喜欢
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多