Невозможно получить push-уведомление от fcm в реагировать на нативный - PullRequest
0 голосов
/ 13 декабря 2018

Я получаю push-уведомление от firebase, но когда я отправил его с помощью "https://fcm.googleapis.com/fcm/send" на android в реагировать на натив с помощью библиотеки реагировать-native-firebase, я не получаю никаких уведомлений на Android. Однако я не могудля отображения сообщения на консоли с помощью метода "onMessage". Но как я могу получить уведомление в панели уведомлений. Мое сообщение только для данных, поэтому я также создал bgMessaging.js для обработки фонового сообщения, и здесь я также могу отображать сообщениев консоли, но не в уведомлении.

Как я могу исправить эту проблему и отобразить сообщение на панели уведомлений с сообщениями только для данных.

Ниже приведен мой код

bgMessaging.js

import firebase from 'react-native-firebase';
// Optional flow type
import type { RemoteMessage } from 'react-native-firebase';

export default async (message: RemoteMessage) => {
    // handle your message
    console.log("message")
    console.log(message)

    // senName = message.data.senderName;
    // senUid = message.data.senderUid;
    // const notification = new 
    // firebase.notifications.Notification()
    //     .setNotificationId('notificationId')
    //     .setTitle(message.data.title)
    //     .setBody(message.data.body)
    //     .android.setChannelId('channel_id_foreground')
    //     .android.setSmallIcon('ic_launcher');
    // firebase.notifications().displayNotification(notification);

    return Promise.resolve();
}

index.js (следующие строки добавлены в конце)

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging); // <-- Add this line

App.js

componentDidMount() {
    this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
      //process data message
      console.log(message);
    });
 }

AndroidManifest.xml

<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
      <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
      </service>  
      <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
        <intent-filter>
          <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
      </service>
      <service android:name=".MyTaskService" />

Ответы [ 3 ]

0 голосов
/ 25 января 2019

App.js

async componentDidMount() {
    this.getToken();
    this.createNotificationListeners();
}

async createNotificationListeners() {
this.notificationListener = firebase.notifications().onNotification((notification) => {
            const { title, body, data } = notification;
            notification
                .android.setChannelId('channel')
                .android.setSmallIcon('icon')
                .android.setAutoCancel(true)
                .android.setPriority(firebase.notifications.Android.Priority.Max)
                .setSound('default');

            firebase.notifications().displayNotification(notification);
        });
}
0 голосов
/ 16 февраля 2019

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

Я обнаружил, что для отображения уведомлений для версии 8+ для Android сначала необходимо создать канал Android, код:

// Create Channel first.
  const channel = new firebase.notifications.Android.Channel(
    "general-channel",
    "General Notifications",
    firebase.notifications.Android.Importance.Default
  ).setDescription("General Notifications");
  firebase.notifications().android.createChannel(channel);

  // Build your notification
  const notification = new firebase.notifications.Notification()
    .setTitle(...)
    .setBody(...)
    .setNotificationId("notification-action")
    .setSound("default")
    .setData(message.data)
    .android.setChannelId("general-channel")
    .android.setPriority(firebase.notifications.Android.Priority.Max);

  // Display the notification (with debug)
  firebase
    .notifications()
    .displayNotification(notification)
    .catch(err => console.error(err));
0 голосов
/ 14 декабря 2018

Вы также можете выполнять действия при отображении уведомления:

firebase.notifications().onNotificationDisplayed(notification => { ... })

или при получении его по телефону:

firebase.notifications().onNotification(notification => { ... })

Если вы хотите получить уведомление, которое сработалопри открытии приложения используйте следующее:

firebase.notifications().getInitialNotification().then(notification => { ... })

см. документ здесь https://rnfirebase.io/docs/v4.3.x/notifications/receiving-notifications

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