1

Добрый день!

Использую Firebase для отправки PUSH уведомлений. Делаю все по инструкции. PUSH уведомления приходят прекрасно. Отправляем их через PHP код, не стандартную консоль. Возник вопрос - как получить сообщение которое было в PUSH уведомлении во время открытия Activity?! Если приложение запущено то приложение попадает в FirebaseMessagingService, где я зашиваю уже в Intent само сообщение и во время открытия Activity получаю его и вывожу, но если приложение не запущено то FirebaseMessagingService не отрабатывает и просто запускается Activity.

Вот пример:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

String TAG = "MyFirebaseMessagingService";

public MyFirebaseMessagingService() {
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());


    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        sendNotification(remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}


private void sendNotification(String messageBody) {

    Intent notificationIntent = new Intent(this, main_activity.class).
            setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notificationIntent.putExtra("NOTIFICATION_MESSAGE", messageBody);

    int requestID = (int) System.currentTimeMillis();

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(main_activity.class);
    stackBuilder.addNextIntent(notificationIntent);
    PendingIntent pendingIntent = stackBuilder.getPendingIntent(requestID, PendingIntent.FLAG_UPDATE_CURRENT);

    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        // only for gingerbread and newer versions
        MyNotificationHelper notificationHelper = new MyNotificationHelper(this);
        Notification.Builder notificationBuilder = notificationHelper.getNotification1(pendingIntent, getString(R.string.notification_title_text), messageBody);

        if (notificationBuilder != null) {
            notificationHelper.notify(1, notificationBuilder);
        }

    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        Notification notification = builder.setContentTitle(getString(R.string.notification_title_text))
                .setContentText(messageBody)
                .setTicker(getString(R.string.notification_title_text))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setSound(soundUri)
                .setAutoCancel(true)
                .build();

        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, notification);
    }

}

}

1 ответ 1

0

Если внимательно прочесть документацию, особенно раздел: https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages то можно узреть табличку, в каких случаях можно перехватывать сообщения в методе onMessageReceived.

Если вкратце, то для реализации Вашей задачи нужно использовать параметр Data и обязательно исключить параметр body, чтоб Вы всегда могли перехватить сообщение в onMessageReceived.

Описание всех доступных параметров можно найти на странице: https://firebase.google.com/docs/cloud-messaging/http-server-ref#data

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.