与Firebase FCM一起使用本机

时间:2018-04-29 14:54:06

标签: javascript firebase react-native firebase-cloud-messaging

我正在尝试通过this documentation使用React Native和Firebase实现推送通知。

我在教程中设置了我需要的设置。

   import React, { Component } from 'react'
import { View } from 'react-native'
import { Input, Text, Button } from '../Components'
import type { RemoteMessage } from 'react-native-firebase'
import firebase from 'react-native-firebase'
import type { Notification, NotificationOpen } from 'react-native-firebase';

export default class TestComponent extends Component {

  async componentDidMount() {
    await this.SetUpAuth();
    await this.SetUpMessaging();
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
      // Get the action triggered by the notification being opened
      const action = notificationOpen.action;
      // Get information about the notification that was opened
      const notification: Notification = notificationOpen.notification;
    });
    const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
      console.log(notificationOpen)
      // App was opened by a notification
      // Get the action triggered by the notification being opened
      const action = notificationOpen.action;
      // Get information about the notification that was opened
      const notification: Notification = notificationOpen.notification;
    }


  }
  componentWillUnmount() {

  }


  async SetUpAuth() {
    const credential = await firebase.auth().signInAnonymouslyAndRetrieveData();
    if (credential) {
      console.log('default app user ->', credential.user.toJSON());
    } else {
      console.error('no credential');
    }
  }
  async SetUpMessaging() {
    this.notification2 = new firebase.notifications.Notification()
      .setNotificationId('notificationId')
      .setTitle('My notification title')
      .setBody('My notification body')
      .android.setChannelId('test')
      .android.setClickAction('action')
      .setData({
        key1: 'value1',
        key2: 'value2',
      });

    this.notification2
      .android.setChannelId('channelId')
      .android.setSmallIcon('ic_launcher');
    console.log('assa')

    onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
      console.log('token generated ->', fcmToken);
      //   store.dispatch(DeviceActions.SetFCMToken(fcmToken));
    });

    const fcmToken = await firebase.messaging().getToken();
    if (fcmToken) {
      // user has a device token
      console.log('has token ->', fcmToken);
      console.log(firebase.auth().currentUser._user)
      firebase.database().ref(`/users/${firebase.auth().currentUser._user.uid}`).set({ pushToken: fcmToken })
      //   store.dispatch(DeviceActions.SetFCMToken(fcmToken));
    } else {
      // user doesn't have a device token yet
      console.error('no messaging token');
    }

    const messagingEnabled = await firebase.messaging().hasPermission();
    if (messagingEnabled) {
      // user has permissions
      console.log('User has FCM permissions');
    } else {
      // user doesn't have permission
      console.log('User does not have FCM permissions');
      await this.RequestMessagePermissions();
    }

    messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
      console.log(`Recieved message - ${JSON.stringify(message)}`);
    });

    notificationDisplayedListener = firebase
      .notifications()
      .onNotificationDisplayed(notification => {
        // 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.
        console.log(`Recieved notification 1`);
      });
    notificationListener = firebase
      .notifications()
      .onNotification(notification => {
        console.log(notification)
        firebase.notifications().displayNotification(this.notification2)
        // Process your notification as required
        console.log(`Recieved notification 2`);
      });
  }


  async RequestMessagePermissions() {
    console.log('request')
    console.log('Requesting FCM permission');
    await firebase
      .messaging()
      .requestPermission()
      .catch(err => console.err(err));
  }


  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>

      </View>
    )
  }

当我尝试在邮递员中使用它时,我获得了成功:

{
  "success": {
    "results": [
        {
            "messageId": "0:1525013439417985%a0cec506a0cec506"
        }
    ],
    "canonicalRegistrationTokenCount": 0,
    "failureCount": 0,
    "successCount": 1,
    "multicastId": 6840884736220792000
  }
}

但是在我的调试器中(通过console.log)我没有看到任何新的传入消息或其他内容。我向我的设备发送了一条消息,上面添加了令牌,但没有发生任何事情。

仅当应用程序位于前台时才有效,但我想在后台应用程序/关闭应用程序时使其工作

3 个答案:

答案 0 :(得分:2)

正如docs中提到的那样onNotificationOpened需要android听众,当应用在后台时

  如果点击通知,则会触发

Android背景onNotificationOpened

onNotificationDisplayed适用于背景中的 IOS应用triggered if content_available set to true

notificationBackgroundListener = firebase
    .notifications()
    .onNotificationOpened(notification => {
      // Process your notification as required
      console.log(`Recieved notification 2`);
    });

答案 1 :(得分:1)

如果您的应用处于前台时通知工作正常,则问题出在您的服务上。它有两个可能的原因不起作用。

  1. 要么将有效负载发送为

    {   
         time_to_live: 86400,
         collapse_key: "xxxxxx",
         delay_while_idle: false,
         registration_ids: registration_ids,
         notification: payload
     }
    

    而不是

      {
           time_to_live: 86400,
            collapse_key: "xxxxxx",
            delay_while_idle: false,
            registration_ids: registration_ids,
            data: payload
      }
    
  2. 这是因为只有当app在前台时才会收到通知中的密钥。

    1. 另一个可能的原因可能是服务工作人员因某种原因被杀。例如:当我强行关闭应用程序时,我正在使用一个加上自动杀死服务的服务。因此,您可以通过添加日志或附加调试器来尝试在本机代码中调试服务
    2. 还要确保在Android / app文件夹中添加google-service.json文件

      修改

      {
       "registration_ids" : ["reg_id"],
       "time_to_live": 86400,
        "collapse_key": "test_type_b",
        "delay_while_idle": false,
      
        "notification": {},   
        "data": {
          "subText":"sub title R",
          "title":"Notification Heading R",
          "message":"Short big text that will be shown when notification is expanded R",
          "color":"red",
          "actions": ["hello", "welcome"],
          "vibrate": true,
          "vibration": 1000,
          "ticker": "My Notification Ticker",
          "imageUrl": "https://cdn-images-1.medium.com/max/712/1*c3cQvYJrVezv_Az0CoDcbA.jpeg" ,
          "bigText": "blalMy big text that will be shown when notification is expanded"
        }
      }
      

      这是我的标题

      Authorization: key=mykey:myKey
      Content-Type: application/json
      

      请求:

       https://fcm.googleapis.com/fcm/send 
      

      是post和params是原始类型

答案 2 :(得分:0)

你可以使用Headless JS在后台运行任务,你应该写一些本机代码来处理任务,不幸的是只在android中可用
https://facebook.github.io/react-native/docs/headless-js-android.html
第二种方式(我不测试它)是使用这个库
https://github.com/jamesisaac/react-native-background-task#installation



ps:firebase和其他推送通知服务,如onesignal轻松处理推送通知,除非你想为每个用户提供独特的通知,否则你不应该担心