Уведомления не отображаются, пока приложение находится на переднем плане - PullRequest
1 голос
/ 02 октября 2019

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

Я пытался сделать некоторый код в методе уведомлений, как предлагается в документации, но он не работает

. Пожалуйста, предложите что-то, что мое приложение может отображать уведомления на переднем плане

Ответы [ 3 ]

1 голос
/ 04 октября 2019

Пожалуйста, перейдите по следующей ссылке.

https://rnfirebase.io/docs/v5.x.x/messaging/android#(Optional)-Background-Messages

Если вы добавили, удалите следующую строку из вашего AndroidManifest.xml.

 <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
0 голосов
/ 04 октября 2019

в моем случае:

import firebase from 'firebase';
import * as Notice from "react-native-firebase";

componentDidMount() {
const firebaseConfig = {
  apiKey: "**********",
  authDomain: "**********",
  databaseURL: "**********",
  projectId: "**********",
  storageBucket: "**********",
  messagingSenderId: "**********",
  appId: "**********"
};
this.mNotifiConfig()
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}
}



mNotifiConfig = async() => {
    Notice.messaging().hasPermission()
      .then(enabled => {
        console.log('HAS PERMISS: ', enabled)
        if (enabled) {
          Notice.messaging().getToken().then(token => {
            console.log("LOG: ", token);
          }).catch(err=> console.log(err))
        } else {
          Notice.messaging().requestPermission()
        }
      });
    const notificationOpen = await Notice
      .notifications()
      .getInitialNotification();
    if (notificationOpen) {
      const action = notificationOpen.action;
      const notification = notificationOpen.notification;
      var seen = [];
      // this.onActionWithNotification(notification)
      console.log('NOTIFICATION IS OPNE')
    }
     // config android
    const channel = new Notice.notifications.Android.Channel(
      "test-channel",
      "Test Channel",
      Notice.notifications.Android.Importance.Max
    ).setDescription("My apps test channel");

// Create the channel
Notice.notifications().android.createChannel(channel);
this.notificationDisplayedListener = Notice
  .notifications()
  .onNotificationDisplayed((notification: Notification) => {
  console.log('CREATED CHANNEL')
    // Process your notification as required
    // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
  });

this.notificationListener = Notice
  .notifications()
  .onNotification((notification: Notification) => {
    console.log('HAS Notification: ', notification)
    // Process your notification as required
    // notification.android
    //   .setChannelId("test-channel")
    //   .android.setSmallIcon("ic_launcher");
    // firebase.notifications().displayNotification(notification).catch(err => console.error(err));

  let notification_to_be_displayed = new Notice.notifications.Notification({
    data: notification.data,
    sound: 'default',
    show_in_foreground: true,
    title: notification.title,
    body: notification.body,
  });
  if(Platform.OS == "android") {
    notification_to_be_displayed
    .android.setPriority(Notice.notifications.Android.Priority.High)
    .android.setChannelId("test-channel")
    .android.setSmallIcon("ic_launcher")
    .android.setVibrate(1000);
}
Notice.notifications().displayNotification(notification_to_be_displayed);
});

this.notificationOpenedListener = Notice
  .notifications()
  .onNotificationOpened((notificationOpen) => {
    // Get the action triggered by the notification being opened
    const action = notificationOpen.action;
    // Get information about the notification that was opened
    const notification = notificationOpen.notification;
    var seen = [];
    console.log('notification Day nay', notification)
    Notice
      .notifications()
      .removeDeliveredNotification(notification.notificationId);
    // this.onLinkingtoApp()
  });

  this.onMessageListener = Notice.messaging().onMessage((message: RemoteMessage) => {
    const {data} = message
    const showNotif = new Notice.notifications.Notification()
      .setNotificationId('notificationId')
      .setTitle(data.title || 'Thông báo')
      .setBody(data.content || 'Bạn có một thông báo mới')
      .setData(data)
      .android.setChannelId('test-channel')
      .android.setSmallIcon('ic_launcher')
      Notice.notifications().displayNotification(showNotif)
  })
}
0 голосов
/ 02 октября 2019

создайте новый файл notifactionHandler.js и импортируйте приведенный ниже код.

import firebase from 'react-native-firebase';

exports.setNotificationListener = () => {
  return new Promise((resolve, reject) => {
    // triggers when notifiaction received while app on foreground
    this.notificationListener = firebase.notifications().onNotification((notification) => { 
      console.log(notification.data);
        setNotification({notification})
    });
    resolve(true);
  })
};

const setNotification = ({notification}) => {
  firebase.notifications().displayNotification(notification);
}

и импортируйте его на свою заставку или главную страницу. затем вызовите функцию setNotificationListener. в основном firebase.notifications (). onNotification перехватывает уведомления, когда приложение находится на переднем плане, и отображает их с помощью firebase.notifications (). displayNotification

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