简体   繁体   English

当 android 应用程序被杀死时,react-native-push-notification 自定义声音不起作用

[英]react-native-push-notification custom sound not working when android app is killed

I have been working on adding custom sounds to push notifications for a react-native app using firebase-admin version ^9.2.0 and react-native-push-notification version ^5.1.0 .我一直在使用 firebase firebase-admin版本^9.2.0react-native-push-notification版本^5.1.0为 react-native 应用程序添加自定义声音来推送通知。

The reason why I haven't upgraded to the latest version of react-native-push-notification is because custom sounds do not seem to work even with proper channel configuration.我没有升级到最新版本的react-native-push-notification的原因是即使使用正确的通道配置,自定义声音似乎也不起作用。 We are also using expo, which appears to be causing a startup error when using version 7+.我们也在使用 expo,这在使用 7+ 版本时似乎会导致启动错误。

I have two mp3 files called regular.mp3 and mass.mp3 .我有两个名为regular.mp3mass.mp3的 mp3 文件。 The firebase functions that send the push notifications send the message using the common data object, but also platform-specific fields for push notification sounds:发送推送通知的 firebase 函数使用公共数据 object 发送消息,但也用于推送通知声音的平台特定字段:

  admin.messaging().send({
    data: {
      title,
      body,
      lat: data.Latitude.toString(),
      lng: data.Longitude.toString(),
      notificationType: data.NotificationType.toString(),
    },
    notification:{title,body},
    apns:{
      payload:{
        aps:{
          alert:{
            title,
            body,
          },
          sound: data.NotificationType === 1 ? "mass.mp3" : "regular.mp3",
        },
      },
    },
    android: {
      priority: "high",
      data: {
        sound: data.NotificationType === 1 ? "mass" : "regular",
      },
      notification: {
        sound: data.NotificationType === 1 ? "mass" : "regular",
      },
    },
    topic: topic,
  })

From my understanding, the data field under android does contain the payload that will be added to the root-level data object when the app is killed and receive the notification.据我了解, android下的data字段确实包含在应用程序被终止并收到通知时将添加到根级data object 的有效负载。 The plugin's source also seems to be using that exact data field to set the notification sound (in RNReceivedMessageHandler.java):该插件的来源似乎也使用该确切的data字段来设置通知声音(在 RNReceivedMessageHandler.java 中):

JSONObject data = getPushData(notificationData.get("data"));

        if (data != null) {
            if (!bundle.containsKey("message")) {
                bundle.putString("message", data.optString("alert", null));
            }
            if (!bundle.containsKey("title")) {
                bundle.putString("title", data.optString("title", null));
            }
            if (!bundle.containsKey("sound")) {
                bundle.putString("soundName", data.optString("sound", null));
            }
            if (!bundle.containsKey("color")) {
                bundle.putString("color", data.optString("color", null));
            }

Here is what I got so far:这是我到目前为止得到的:

  • custom sounds work great when the app is in foreground当应用程序处于前台时,自定义声音效果很好
  • custom sounds work great when app is in background当应用程序在后台时,自定义声音效果很好
  • default sound plays when app is killed应用程序被杀死时播放默认声音

Here is the code currently in place to manage the notifications:这是当前用于管理通知的代码:

In index.ts:在 index.ts 中:

PushNotification.configure({
  // (optional) Called when Token is generated (iOS and Android)
  onRegister: function(token) {
      console.log("TOKEN:", token);
  },


  // (required) Called when a remote is received or opened, or local notification is opened
  onNotification: function(notification) {
      console.log("NOTIFICATION:", notification);

      // process the notification

      // (required) Called when a remote is received or opened, or local notification is opened
      //notification.finish(PushNotificationIOS.FetchResult.NoData);
  },

  // (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
  onAction: function(notification) {
      console.log("ACTION:", notification.action);
      console.log("NOTIFICATION:", notification);

      // process the action
  },

  // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
  onRegistrationError: function(err) {
      console.error(err.message, err);
  },

  // IOS ONLY (optional): default: all - Permissions to register.
  permissions: {
      alert: true,
      badge: true,
      sound: true,
  },
  popInitialNotification: true,
  requestPermissions: true,
});

In App.js在 App.js 中

  CreateIncidentPushNotification=(remoteMessage)=>{
    const {data} = remoteMessage;
    PushNotification.localNotification({
      title: data.title,
      message: data.body,
      playSound: true,
      soundName: data.notificationType === "1" ? "mass" : "regular",
    });
  }

I was wondering if anyone else had an idea about what could be going on.我想知道是否有其他人对可能发生的事情有所了解。 The notification still manages to get to my device even when the app is killed, which is great.即使应用程序被终止,通知仍然可以到达我的设备,这很棒。 The only missing part is the sound.唯一缺少的部分是声音。

Okay so I finally got it working.好的,所以我终于让它工作了。 I had to add the following to my manifest file and comment a receiver:我必须在清单文件中添加以下内容并注释接收器:


      <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
                android:value="my-channel"/>
      <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
                  android:value="my channel"/>

      <!-- 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 value to false if you don't want the creation of the default channel -->
      <meta-data  android:name="com.dieam.reactnativepushnotification.channel_create_default"
                  android:value="true "/>
      <!-- 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" />
          </intent-filter>
      </receiver> -->

Then, I had to use channels in order to get the sounds working in foreground, background, and when the app is killed.然后,我不得不使用通道来让声音在前台、后台和应用程序被终止时工作。 As you can see, I created a custom channel in my manifest file and activated the default channel as well.如您所见,我在清单文件中创建了一个自定义频道并激活了默认频道。 I HAD to activate the default channels because I have two notification types that require different sounds.我必须激活默认频道,因为我有两种需要不同声音的通知类型。 Using a single channel was NOT WORKING.使用单个通道不起作用。

Once the manifest file has been updated, I modified the firebase functions (using firebase-admin to do the following:清单文件更新后,我修改了 firebase 函数(使用 firebase firebase-admin执行以下操作:

  admin.messaging().send({
    data: {
      title,
      body,
      lat: data.Latitude.toString(),
      lng: data.Longitude.toString(),
      notificationType: data.NotificationType.toString(),
    },
    notification:{title,body},
    apns:{
      payload:{
        aps:{
          alert:{
            title,
            body,
          },
          sound: data.NotificationType === 1 ? "mass.mp3" : "regular.mp3",
        },
      },
    },
    android: {
      priority: "high",
      data: {
        sound: data.NotificationType === 1 ? "mass" : "regular",
        channelId: data.NotificationType === 1 ? "my-channel" : "fcm_fallback_notification_channel",
      },
      notification: {
        sound: data.NotificationType === 1 ? "mass" : "regular",
        channelId: data.NotificationType === 1 ? "my-channel" : "fcm_fallback_notification_channel",
      },
    },
    topic: topic,
  })
  .then((response) => {
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Firebase was now aware of the two channels I was using. Firebase 现在知道我正在使用的两个通道。 I then moved to the application code and handled the local notification like this:然后我转到应用程序代码并像这样处理本地通知:

    PushNotification.localNotification({
      title: data.title,
      message: data.body,
      playSound: true,
      soundName: data.notificationType === "1" ? "mass" : "regular",
      channelId: data.notificationType === "1" ? "my-channel" : "fcm_fallback_notification_channel"
    });

I also activated both onMessage and setBackgroundMessageHandler handlers of the react-native-push-notification package:我还激活了react-native-push-notification package 的onMessagesetBackgroundMessageHandler处理程序:

        messaging().onMessage(this.sendMessage);
        messaging().setBackgroundMessageHandler(this.sendMessage);

Where this.sendMessage is responsible to call the localNotification call mentioned above.其中this.sendMessage负责调用上面提到的localNotification调用。

By the way, I am stil getting duplicated notifications when the app is in background, so this is purely a fix for the sounds.顺便说一句,当应用程序处于后台时,我仍然会收到重复的通知,所以这纯粹是对声音的修复。

UPDATE: removing the setBackgroundMessageHandler removed the duplicates:!!!更新:删除setBackgroundMessageHandler删除了重复项:!!! :) Peace! :) 和平!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当应用程序在后台并单击通知时,Android react-native-push-notification onNotification 没有被调用? - Android react-native-push-notification onNotification not called when app is in the background and notification clicked? 将senderID添加到react-native-push-notification配置时,react本地应用程序立即崩溃 - react native app instantly crashes when adding senderID to react-native-push-notification configure 使用 react-native-push-notification,App 在收到新的 FCM 通知时崩溃 - Using react-native-push-notification, App crashes when receiving new FCM notification 自定义声音未在clevertap推送通知中播放反应原生Android项目 - Custom sound not playing in clevertap push notification react native android project 如果应用程序被杀死,则解析推送通知不起作用(Android) - Parse Push notification not working if app is killed (Android) 使用 react-native-push-notification 删除以前的通知 - Delete previous notification(s) using react-native-push-notification “ react-native-push-notification”包在Android上导致多个dex调试错误 - “react-native-push-notification” package causing multiple dex debug error on android 如何在Android上用react-native-push-notification获取所有通知,相当于PushNotificationIOS getDeliveredNotifications? - How to get all notifications with react-native-push-notification on Android, equivalent to PushNotificationIOS getDeliveredNotifications? Android Firebase 推送通知自定义声音不起作用 - Android Firebase push notification custom sound is not working Android 推送通知的自定义声音不起作用 (FCM) - Custom sound for Android Push Notification not working (FCM)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM