1

为了探索 FCM 推送通知原理,我开发了一个基本应用程序。当我的应用程序处于前台时,一切都按预期进行,通知由 _createNotificationListeners() 函数处理。但是,当应用程序处于后台或终止 bgMessaging 文件中的代码时,本应处理传入通知的代码根本没有任何效果。

当我的应用程序被杀死时,我应该怎么做才能处理通知?

应用程序.js

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import firebase from 'react-native-firebase';


export default class PushAgain extends Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>My Basic Push Notification App !</Text>
      </View>
    );
  }

  async _getToken() {
      let fcmToken = await AsyncStorage.getItem('fcmToken');
      if (!fcmToken) {
      fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
          await AsyncStorage.setItem('fcmToken', fcmToken);
      }
      }

      console.log('fcmToken:', fcmToken);
  }

  async _checkPermission() {
      const enabled = await firebase.messaging().hasPermission();
      if (enabled) {
      this._getToken();
      } else {
      this._requestPermission();
      }
  }

  async _requestPermission() {
      try {
      await firebase.messaging().requestPermission();
      this._getToken();
      } catch (error) {
      console.log('permission rejected');
      }
  }

  async _createNotificationListeners() {
      firebase.notifications().onNotification(notification => {
      notification.android.setChannelId('insider').setSound('default');

      firebase.notifications().displayNotification(notification);
      console.log('Notification title:', notification.title);
      });
  }

  async componentDidMount() {
    // Build a channel.
    const channel = new firebase.notifications.Android.Channel('insider', 'insider channel', firebase.notifications.Android.Importance.Max)
    // Create the channel.
    firebase.notifications().android.createChannel(channel);
    this._checkPermission();
    this._createNotificationListeners();
  }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.pushagain">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

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

      <meta-data
       android:name="com.google.firebase.messaging.default_notification_channel_id"
       android:value="@string/default_notification_channel_id" />

    <!-- Background Messages (Optional) -->

      <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
      <intent-filter>
          <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
      </intent-filter>
      </receiver>
      <service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/>

    </application>

</manifest>

字符串.xml

<resources>
    <string name="app_name">PushAgain</string>
    <string name="default_notification_channel_id" translatable="false">fcm_default_channel</string>
</resources>

index.js

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import bgMessaging from './src/bgMessaging';

AppRegistry.registerComponent(appName, () => App);
// New task registration
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging);

bgMessaging.js

import firebase from 'react-native-firebase';
// Optional flow type
import type { RemoteMessage } from 'react-native-firebase';

export default async (message: RemoteMessage) => {
  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);

  const notification = new firebase.notifications.Notification()
  .setNotificationId(message.messageId)
  .setTitle('bgMessaging notification')
  .setBody('Notification handled in bgMessaging')
  .setSound(message.data.sound);

  notification
  .android.setChannelId('test-channel')
  .android.setSmallIcon('ic_launcher');

  firebase.notifications().displayNotification(notification);

    return Promise.resolve();
}
4

0 回答 0