Реагировать на родной с Firebase FCM - PullRequest
0 голосов
/ 29 апреля 2018

Я пытаюсь реализовать push-уведомления с помощью 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 голосов
/ 02 мая 2018

Как уже упоминалось в документах , вам нужно 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`);
    });
0 голосов
/ 08 мая 2018

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

  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
      }
    

, потому что ключ в уведомлении получен только тогда, когда приложение находится на переднем плане.

  1. Другой возможной причиной может быть то, что работника службы по какой-то причине убивают. пример: я использовал один плюс, который автоматически убивает сервис, когда я принудительно закрываю приложение. Таким образом, вы можете попробовать отладить службу в собственном коде, добавив журнал или подключив отладчик

также обязательно добавьте файл google-service.json в папку android / app

Редактировать

{
 "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 

, который имеет столбец, а params - необработанный тип

0 голосов
/ 02 мая 2018

вы можете использовать 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 и другие сервисы push-уведомлений, такие как onesignal, легко обрабатывают push-уведомления, и вам не следует беспокоиться, если вы не хотите получать уникальные уведомления для каждого пользователя

...