Метод onMessageReceived в FirebaseMessagingService не вызывается - PullRequest
0 голосов
/ 10 октября 2019

Я отправляю уведомление, используя облачную функцию Firebase. Когда я отправляю данные с ключом уведомления, отправляется уведомление, но метод не вызывается. Но с ключом данных ничего не произошло.

Вот мой код для FirebaseMessagingService

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {


        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));


            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }

    }

    private void sendNotification(String title, String messageBody){

        String channelId = getString(R.string.default_notification_channel_id);

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_logo)
                        .setContentTitle(title)
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0 , notificationBuilder.build());

    }

Вот моя облачная функция Firebase

exports.sendNotification = functions.database
  .ref("/deals/{userId}/{dealId}")
  .onCreate((data, context) => {
    const dataValue = data.val();

    const topic = context.params.userId;

    const payload = {
      data: {
        title: "New deal created",
        body: dataValue.user.name + " added a new deal."
      },
      topic: topic
    };

    // Send a message to devices subscribed to the provided topic.
    return admin
      .messaging()
      .send(payload)
      .then(response => {
        // Response is a message ID string.
        console.log("Successfully sent message:", response);
      })
      .catch(error => {
        console.log("Error sending message:", error);
      });
  });

Также я настроил точку отладкиonMessageReceived (), но он не запустился.

Ответы [ 2 ]

0 голосов
/ 16 октября 2019

Когда ваше приложение работает в фоновом режиме, Firebase не будет запускать OnMessageReceived, вместо этого будет отображаться уведомление с уведомлением

+

убедитесь, что вы подписались на правильную тему

+

убедитесь, что сервисы воспроизведения обновлены на вашем устройстве.

0 голосов
/ 16 октября 2019

Я разобрался в проблеме. Проблема в том, что после внесения некоторых изменений и создания проекта Android нам нужно снова подписаться на тему.

...