Android Уведомления - заменить одно уведомление другим - PullRequest
0 голосов
/ 26 января 2020

Я создаю приложение React Native, в котором при некоторых обстоятельствах мне нужно заменить уведомление, содержащее только данные, которое было отправлено от одного клиента другому.

Я понимаю, что с сообщениями только с данными клиент обрабатывает уведомление. Я прочитал, что уведомление может быть заменено или отменено, если получено другое с тем же идентификатором уведомления.

Однако я не понимаю, что, по-видимому, клиент-получатель несет ответственность за создание идентификатора уведомления. ?

Это код java, который обрабатывает входящее облачное сообщение Firebase:

@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);
    }
}

Как только уведомление создано, как я могу узнать идентификатор уведомления в отправляющем клиенте, например что я могу заменить существующий?

Вот мой код, который отправляет уведомления:

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) {
  });
}

Как видите, мое понимание того, как именно это работает, любая помощь очень ценится!

1 Ответ

1 голос
/ 26 января 2020
int notificationCode = (int) (Math.random() * 1000);

Просто не создавайте случайный идентификатор уведомления, вместо этого используйте постоянный идентификатор, такой как

int notificationCode = 5;

Если вы хотите, чтобы уникальные уведомления были для каждого клиента, вы можете упаковать уведомления в своем сообщении данных, из сторона отправителя (например, используя идентификатор пользователя в качестве идентификатора уведомления) и использовать его в качестве уведомления (полученного из сообщения данных), новые уведомления от того же клиента будут автоматически заменены.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...