【问题标题】:Is it necessary to use FLAG_ACTIVITY_NEW_TASK in a Notification's PendingIntent?是否有必要在通知的 PendingIntent 中使用 FLAG_ACTIVITY_NEW_TASK?
【发布时间】:2012-08-17 06:50:33
【问题描述】:

我使用Notifications 有一段时间了,昨天我注意到PendingIntent 的文档说传递给PendingIntent.getActivity()方法的Intent 必须有FLAG_ACTIVITY_NEW_TASK 集:

请注意,活动将在 现有活动,因此您必须使用 Intent.FLAG_ACTIVITY_NEW_TASK Intent 中的启动标志。

但是,我在使用Notifications 时从未设置此标志,但到目前为止我还没有遇到任何问题。我已经看到了几个Notifications 的例子,其中FLAG_ACTIVITY_NEW_TASK 没有为PendingIntent 引用的Intent 设置。特别是,official guide 显示了下面的 sn-p:

Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

如您所见,他们没有设置FLAG_ACTIVITY_NEW_TASK 标志。所以我的问题是,我应该在使用PendingIntent.getActivity() 时始终设置FLAG_ACTIVITY_NEW_TASK 标志,还是在某些情况下可以省略它?特别是在使用Notifications的时候,可以不设置这个flag就使用Intent吗?

【问题讨论】:

    标签: android android-pendingintent


    【解决方案1】:

    我相信系统会为您设置通知。从通知启动时,您将获得一个新任务。

    【讨论】:

      【解决方案2】:

      是的,您应该使用FLAG_ACTIVITY_NEW_TASK。否则,您可能会在某些设备上出现意外行为。

      截至今天(2017 年 3 月 25 日)official guide linked in the question 已更新代码 sn-p:

      // Creates an Intent for the Activity
      Intent notifyIntent =
              new Intent(this, ResultActivity.class);
      // Sets the Activity to start in a new, empty task
      notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                              | Intent.FLAG_ACTIVITY_CLEAR_TASK);
      // Creates the PendingIntent
      PendingIntent notifyPendingIntent =
              PendingIntent.getActivity(
              this,
              0,
              notifyIntent,
              PendingIntent.FLAG_UPDATE_CURRENT
      );
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2019-04-25
      相关资源
      最近更新 更多