Уведомления FCM не принимаются - PullRequest
0 голосов
/ 12 октября 2019

React Native Version: 0.60.5

React Native Firebase Версия: 5.5.6

Android Native Firebase Версия: 17.0.0

dependencies{
    implementation project(':react-native-firebase')
...
    implementation 'com.google.firebase:firebase-core:17.0.0'
    implementation 'com.google.firebase:firebase-messaging:19.0.1'
...
}

MainApplication.java

    protected List<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      packages.add(new RNFirebaseMessagingPackage());
      packages.add(new RNFirebaseNotificationsPackage());
      return packages;
      }

AndroidManifest.xml

  <meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_name" android:value="shwoop-adventure-app"/>
    <meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_description" android:value="Notifications for the shwoop app"/>
    <meta-data android:name="com.dieam.reactnativepushnotification.notification_color" android:resource="@color/appPrimary"/>

    <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/logo1024"/>
    <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/appPrimary"/>
    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_channel"/>

    <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
    <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
      </intent-filter>
    </receiver>

    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
    <intent-filter>
      <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
  </service>
  <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
    <intent-filter>
      <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
  </service>

Реагировать на собственную обработку Firebase

import firebase, { Notification, RemoteMessage } from 'react-native-firebase';
import { Platform } from 'react-native';
import { logger } from '@react-native-community/cli-tools';


// add following code to an appropriate place.
// implement notifications as needed
async function setupNotifications(this: any) {
  // Build a channel
  const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
    .setDescription('My apps test channel');

  // Create the channel
  firebase.notifications().android.createChannel(channel);
  if(Platform.OS === 'android') {
    try {
      const res = await firebase.messaging().requestPermission();
      const fcmToken = await firebase.messaging().getToken();

      if(fcmToken) {
        console.log('FCM Token: ', fcmToken);

        const enabled = await firebase.messaging().hasPermission();
        if(enabled)
          logger.log('FCM messaging has permission:' + enabled);

        else {
          try {
            await firebase.messaging().requestPermission();
            logger.log('FCM permission granted');
          }
          catch(error) {
            logger.log('FCM Permission Error', error);
          }
        }
        firebase.notifications().onNotificationDisplayed((notification: 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('Notification: ', notification);
        });

        this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
          console.log('Not displayed');
          console.log('Notification: ', notification);
        });

        console.log('Lets send a notification');

        const notification = new firebase.notifications.Notification()
          .setNotificationId('notificationId')
          .setTitle('My notification title')
          .setBody('My notification body')
          .android.setChannelId('test-channel')
          .setSound('default');

        firebase.notifications().displayNotification(notification);
        firebase.messaging().onMessage(() => console.log('Something happened.'));

      }
      else
        logger.log('FCM Token not available');

    }
    catch(e) {
      logger.log('Error initializing FCM', e);
    }
  }
}

setupNotifications();

Проблема:

Нет уведомлений, поступающих на устройство. Я использую консоль Firebase Cloud Messaging для отправки сообщения на мое устройство с помощью токена FCM, предоставленного firebase.messaging().getToken();. Я был на этом весь день, и не могу определить, почему уведомление не приходит на устройство. Уведомление, сгенерированное в этом файле, однако, отображается и проходит через функцию onNotificationDisplayed().

Я следовал руководству по React Native Firebase и, похоже, не вижу, где я ошибаюсь. Я подозреваю, что это не связано с RNFirebase, а больше с моим AndroidManifest, но ни одно из моих изменений не помогло.

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