【问题标题】:Starting Activity through notification: Avoiding duplicate activities通过通知启动活动:避免重复活动
【发布时间】:2018-01-03 01:19:12
【问题描述】:

所以我目前正在显示一个通知。当用户单击此通知时,应用程序将启动。通知持续存在,表明该服务正在后台运行。

Intent notificationIntent = new Intent(context, LaunchActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);

但是,我检测到出现错误的情况。如果用户通过单击普通图标启动应用程序,并且在活动运行时单击通知,则将启动一个新活动,而不退出较早的活动,较晚的活动位于较早的活动之上。这还不是全部:进一步点击通知将创建额外的活动,并将它们放在已经运行的活动之上。我怎样才能防止这种情况?是否有一个很好的检查来查看当前是否正在显示或加载某个活动?

【问题讨论】:

    标签: android


    【解决方案1】:

    这就是它应该默认的方式。如果您只想拥有一个实例,您可能需要指定 android:launchMode="singleTop"
    有 4 种启动模式,更多信息在这里:https://developer.android.com/guide/topics/manifest/activity-element.html

    【讨论】:

    • 将其设置为“singleTask”解决了我的问题。感谢您帮助我!
    【解决方案2】:

    使用lanchMode="singleTask" 时,如果您的Activity 实例已经存在,Android 不会重新创建该Activity,而是使用onNewIntent() 方法启动它。

    由 Android 记录:

    系统在新任务的根目录创建活动并将意图路由到它。但是,如果 Activity 的实例已经存在,系统会通过调用其 onNewIntent() 方法将 Intent 路由到现有实例,而不是创建一个新实例。

    Android documentation for activity mode

    【讨论】:

      【解决方案3】:

      正如上面的两个答案所提到的,您需要设置应用程序的启动模式,该模式在清单中的活动定义中定义:

      <activity
          android:name="com.company.ActivityName"
          android:launchMode="singleTask">
      </activity>
      

      此外,您可能需要注意,尽管 FLAG_ACTIVITY_SINGLE_TOP 是有效的 Intent 标志,但对于 singleTask 或 singleInstance 没有等效的 Intent 标志。

      有关不同启动模式选项的更多详细信息,请参阅 launchMode 部分:http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

      【讨论】:

      • FLAG_ACTIVITY_NEW_TASK 不等同于 singleTask 吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多