React Native-无法在Android的前台访问Firebase推送通知

时间:2019-02-23 12:56:05

标签: android firebase react-native push-notification firebase-cloud-messaging

我正在尝试通过遵循以下文章在具有Firebase控制台应用程序的React Native中实现推送通知:

React Native: Integrating Push Notifications using FCM

在Android中,当应用程序在后台但无法在前台接收时,我可以接收通知。使用此方法来接收通知:

async createNotificationListeners() {
  /*
   * Triggered when a particular notification has been received in foreground
   * */
  this.notificationListener = firebase
    .notifications()
    .onNotification(notification => {
      console.log("fg", notification);
      const { title, body } = notification;
      this.showAlert(title, body);
    });

  /*
   * If app is in background, listen for when a notification is clicked / tapped / opened as follows:
   * */
  this.notificationOpenedListener = firebase
    .notifications()
    .onNotificationOpened(notificationOpen => {
      console.log("bg", notificationOpen);
      const { title, body } = notificationOpen.notification;
      this.showAlert(title, body);
    });

  /*
   * If app is closed, check if it was opened by a notification being clicked / tapped / opened as follows:
   * */
  const notificationOpen = await firebase
    .notifications()
    .getInitialNotification();
  if (notificationOpen) {
    console.log("bg", notificationOpen);
    const { title, body } = notificationOpen.notification;
    this.showAlert(title, body);
  }
  /*
   * Triggered for data only payload in foreground
   * */
  this.messageListener = firebase.messaging().onMessage(message => {
    //process data message
    console.log("fg", JSON.stringify(message));
  });
}

此处, firebase.notifications().onNotification firebase.messaging().onMessage() 根本没有被触发。

在其他解决方案中,这是因为从Android 8开始,您需要创建一个频道,但是在从FCM notification composer发送通知时,找不到任何创建频道的选项。

1 个答案:

答案 0 :(得分:1)

阿卜杜勒

您需要使用设备上的Firebase来创建通知通道。

const channel = new firebase.notifications.Android
  .Channel('default', 'Default Channel', firebase.notifications.Android.Importance.Max)
  .setDescription('The default notification channel.')

firebase.notifications().android.createChannel(channel)

这将创建频道,您可以根据需要安全地调用它多次(根据文档)。您的onNotification侦听器看起来不错,您只需要在传入的通知中设置android频道即可。

  notification.android.setChannelId('default')