Android 通知 - 将一个通知替换为另一个

Android Notifications - replace one notification with another

我正在构建一个 React Native 应用程序,在某些情况下,我需要替换已从一个客户端发送到另一个客户端的仅数据通知。

我了解只有数据消息才会由客户端处理通知。我了解到,如果收到另一个具有相同通知 ID 的通知,则可以替换或取消通知。

但是,我不明白的是,接收客户端似乎负责创建通知 ID?

这是处理传入的 firebase 云消息的 java 代码:

@ReactMethod
    void navigateToExample(String notificationMessage) {
        ReactApplicationContext context = getReactApplicationContext();

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder;

        Resources res = context.getResources();

        // начиная с Android 8, требуются каналы уведомлений
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            String CHANNEL_ID = "channel_ID_0";

            // https://developer.android.com/training/notify-user/channels
            // https://medium.com/exploring-android/exploring-android-o-notification-channels-94cd274f604c
            // https://startandroid.ru/ru/uroki/vse-uroki-spiskom/515-urok-190-notifications-kanaly.html
            // https://code.tutsplus.com/ru/tutorials/android-o-how-to-use-notification-channels--cms-28616

            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel",
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("channel description");
            manager.createNotificationChannel(channel);

            builder = new NotificationCompat.Builder(context, CHANNEL_ID);
        } else {
            builder = new NotificationCompat.Builder(context);
        }

        // Flag indicating that if the described PendingIntent already exists, the
        // current one should be canceled before generating a new one.
        Intent activityIntent = new Intent(context, MainActivity.class);
        activityIntent.putExtra("FromNotification", true);
        PendingIntent action = PendingIntent.getActivity(context, 0, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        // make this notification automatically dismissed when the use touches it
        builder.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_announcement_black_24dp))
                .setSmallIcon(R.drawable.ic_announcement_black_24dp).setTicker("Large text!").setAutoCancel(true)
                .setContentTitle(notificationMessage).setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_CALL).setContentText("Tap to answer or reject the call")
                .setFullScreenIntent(action, true);

        Notification notification = builder.build();

        int notificationCode = (int) (Math.random() * 1000);
        manager.notify(notificationCode, notification);
    }
}

创建通知后,我如何才能知道发送客户端中的通知 ID,以便替换现有通知?

这是我发送通知的代码:

export const subscribeToPushNotifications = async () => {

  const fcmToken = await firebase.messaging().getToken();
  console.log(fcmToken);

  if (fcmToken) {
    // user has a device token
    const params = {
      notification_channels: Platform.OS === 'ios' ? 'apns' : 'gcm',
      device: {
        platform: Platform.OS,
        udid: DeviceInfo.getUniqueId(),
      },
      push_token: {
        environment: 'production',
        client_identification_sequence: fcmToken,
      }
    }

    ConnectyCube.pushnotifications.subscriptions.create(params, function (error, result) {
      // console.log(error); // errors: ["Token is required"]
      // console.log(result);
    });

    receiveFCMs();

  } else {
    // user doesn't have a device token yet
  }
}

export const sendNotification = async (calleeId, callLength, tagUUID) => {

  const callersUserName = await getUserNameFromStorage();

  const payload = JSON.stringify({
    message: callersUserName + '-' + callLength,
    tag: tagUUID,
  });

  const pushParameters = {
    notification_type: 'push',
    user: { ids: [calleeId] }, // recipients.
    environment: 'production', // environment, can be 'production'.
    message: ConnectyCube.pushnotifications.base64Encode(payload)
  };

  ConnectyCube.pushnotifications.events.create(pushParameters, function (error, result) {
  });
}

如您所见,我完全了解其工作原理,非常感谢任何帮助!

int notificationCode = (int) (Math.random() * 1000);

不要创建随机通知 ID,而是使用像

这样的常量 ID
int notificationCode = 5;

如果你想为每个客户端发送唯一的通知,你可以在你的数据消息中打包 notificationid,从发件人端(比如使用 userid 作为通知 id)并将其用作 notificationid(从数据消息接收),来自相同的新通知客户端将被自动替换。