【问题标题】:Notifications are not showing while the app is in foreground应用程序在前台时不显示通知
【发布时间】:2019-10-02 06:09:01
【问题描述】:

当我的应用程序关闭或在后台时,我试图通过 firebase 控制台使用 react-native-firebase 发送推送通知,收到通知并显示为弹出窗口,但如果我的应用程序在前台,通知没有出现

我一直在尝试按照文档中的建议在通知方法中编写一些代码,但它不起作用

请建议我的应用可以在前台显示通知

【问题讨论】:

    标签: react-native push-notification react-native-firebase


    【解决方案1】:

    就我而言:

    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)
      })
    }
    

    【讨论】:

      【解决方案2】:

      请参考以下链接。

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

      如果您已添加,请从您的 AndroidManifest.xml 中删除以下行。

       <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
      

      【讨论】:

        【解决方案3】:

        创建一个新的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 显示它

        【讨论】:

        • 非常感谢 Arenak 我会试试这个并通知你:)
        猜你喜欢
        • 2021-12-13
        • 2018-11-08
        • 1970-01-01
        • 2017-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多