React Native 推送通知无法正常工作

React Native Push Notification Not Working Properly

推送通知功能:

PushNotification.configure({
  largeIcon: "ic_launcher",
  smallIcon: "ic_notification",
  onNotification: function (notification) {
    PushNotification.localNotification({
      autoCancel: true,
      message: 'Test Message',
      title: 'Test Message',
      vibrate: true,
      vibration: 300,
      playSound: true,
      soundName: 'default'
    })
    console.log(notification)
  },
});

问题:

  1. 当我 运行 应用程序时,如果我从 php 服务器发送通知,我会在 console.log
  2. 中收到响应

但是

条件 1:PushNotification.localNotification() 前景不工作。

条件 2:PushNotification.localNotification() 后台不工作。

  1. 如果我从 firebase 服务器发送通知,我会在 console.log
  2. 中收到响应

但是

条件 3:PushNotification.localNotification() 前景不工作。

条件 4:PushNotification.localNotification() 后台工作。

在我从 firebase 服务器收到第一个通知后,即条件 4,我的应用程序也开始接收来自所有其他 3 个条件的通知,如上所述。奇怪,但我测试了很多次

  1. 如果我点击通知,通知栏中仍然可见
  2. 并且在 OnePlus9 设备上,整体通知不起作用。

我收到来自 php 服务器的响应:

    {
       "data": 
       {
          "message": "Your order with order no OID63112 has been dispatched. Expected time for arrival is 30 min", 
           "title": "Picked up order", 
           "vibrate": "1"
       }, 
       "from": "326331584681", 
       "messageId": "0:1607089521078208%d58aa421f9fd7ecd", 
       "sentTime": 1607089521064, 
       "ttl": 2419200
   }

我收到来自 firebase 服务器的响应:

   {   
       "channelId": "fcm_fallback_notification_channel", 
       "color": null, 
       "data": {}, 
       "finish": [Function finish], 
       "foreground": true, "id": "-1787502606", 
       "message": "Enjoy your meat! Order Online!",
       "priority": "high", 
       "sound": null, 
       "tag": "campaign_collapse_key_4040075812614528488", 
       "title": "Freshcut", 
       "userInteraction": false, 
       "visibility": "private"
    }

我的配置是

"@react-native-firebase/app": "^8.4.7",
    "@react-native-firebase/crashlytics": "^8.4.9",
    "@react-native-firebase/database": "^10.0.0",
    "@react-native-firebase/messaging": "^7.9.0",
    "react-native-push-notification": "^6.1.3",

android/build.gradle

 ext {
        buildToolsVersion = "29.0.2"
        minSdkVersion = 19
        compileSdkVersion = 29
        targetSdkVersion = 29
        googlePlayServicesVersion = "+" // default: "+"
        firebaseMessagingVersion = "+" // default: "+"
    }

android/app/src/main/AndroidManifest.xml

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <permission
        android:name="com.freshcut.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.freshcut.permission.C2D_MESSAGE" />
<!-- Change the value to true to enable pop-up for in foreground (remote-only, for local use ignoreInForeground) -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>
        <!-- Change the resource name to your App's accent color - or any other color you want -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@color/white"/> <!-- or @android:color/{name} to use a standard color -->
 
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
        <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" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>
 
        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

我无法找到确切的问题,我也阅读了所有其他问题并尝试了不同的解决方案但没有解决。 我是 react-native-puch-notification 的新手。

您必须订阅 firebase 通知才能接收通知。因此,首先使用 onMessage() 消息传递方法订阅 firebase 通知。每当从 firebase 收到消息时订阅后,触发 localNotification 以在前台弹出更多通知,其中包含您在 remoteMessage 中收到的标题、消息和其他数据,如下所示:

useEffect(() => {
  const unsubscribe = messaging().onMessage(async (remoteMessage) => {
    PushNotification.localNotification({
      message: remoteMessage.notification.body,
      title: remoteMessage.notification.title,
      bigPictureUrl: remoteMessage.notification.android.imageUrl,
      userInfo: remoteMessage.data,
    });
  });

  return unsubscribe;
}, []);

为您的通知频道定义一个名称它可以是任何东西,您将使用它从您的推送消息中定位您的自定义频道,以便您将绑定到您的频道播放的自定义声音。 我应该注意,安装应用程序后,频道名称将保持注册状态,直到应用程序被卸载。因此,如果您以后更改频道名称,请记住这一点。

添加您的声音作为资源将您的 .wav 声音拖到 your_project_root/android/app/src/main/res/raw 文件夹中(如果不存在,请创建它)。 添加通知渠道代码:

首先添加所有 MainActivity 导入

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;

下面的代码必须放在 MainActivity 的 onCreate 方法中 class。用您自己的方式填写括号中的文本,并自定义通知中需要的任何其他内容:

@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      NotificationChannel notificationChannel = new NotificationChannel("my_default_channel", "Tallo", NotificationManager.IMPORTANCE_HIGH);
      notificationChannel.setShowBadge(true);
      notificationChannel.setDescription("");
      AudioAttributes att = new AudioAttributes.Builder()
              .setUsage(AudioAttributes.USAGE_NOTIFICATION)
              .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
              .build();
      notificationChannel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/sample"), att);
      notificationChannel.enableVibration(true);
      notificationChannel.setVibrationPattern(new long[]{400, 400});
      notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
      NotificationManager manager = getSystemService(NotificationManager.class);
      manager.createNotificationChannel(notificationChannel);
    }
  }
Here’s a code example with some values filled in

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          NotificationChannel notificationChannel = new NotificationChannel("new_email_arrived_channel", "My Emailer", NotificationManager.IMPORTANCE_HIGH);
          notificationChannel.setShowBadge(true);
          notificationChannel.setDescription("");
          AudioAttributes att = new AudioAttributes.Builder()
                  .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                  .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                  .build();
          notificationChannel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/my_custom_sound"), att);
          notificationChannel.enableVibration(true);
          notificationChannel.setVibrationPattern(new long[]{400, 400});
          notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
          NotificationManager manager = getSystemService(NotificationManager.class);
          manager.createNotificationChannel(notificationChannel);
      }

设置推送主体现在您的请求已配置,让我们添加推送主体。这是在数据类型选项下空白区域的正文选项卡中完成的。这是一个示例正文:

{
    "to": "<FCM TOKEN>",
    "notification": {
      "title": "Some title",
        "body": "Some body",
        "sound": "my_custom_sound.wav",
        "android_channel_id": "new_email_arrived_channel"
    },
    "data": {
        "field1": "value1",
        "field2": "value2"
    },
    "content_available": true,
    "priority": "high"
}