繁体   English   中英

Android 推送通知的自定义声音不起作用 (FCM)

[英]Custom sound for Android Push Notification not working (FCM)

我有使用来自云 function 的 FCM 的推送通知。这适用于 iOS 和 Android,并显示适当的图标并在 iOS 上播放自定义声音。

除了 Android 的自定义声音外,一切正常,它只是播放默认声音。

我创建了一个文件夹并将我的声音文件添加到其中,如下所示: android\app\src\main\res\raw\mp3_example.mp3

这个 mp3 长 27 秒。 我也试过 a.wav 和.aiff。

我读到我可能必须为 Android 的更高版本创建一个推送通知通道,所以它可能与此相关。 我尝试创建一个频道并使用来自云 function 的 channelID 并且它有效但没有声音只是振动。

测试设备是运行 Android 8 的 Moto G6。我正在使用:FCM Firebase Cloud Functions Ionic 4 Capacitor https://github.com/stewwan/capacitor-fcm

云Function:

const notification: admin.messaging.Notification = {
      title: title,
      body: body
  }

  const message: admin.messaging.Message = {
    notification,
    topic: 'QMTBC',
    android:{
      notification:{
        sound: 'mp3_example.mp3',
        icon: 'push_logo',
        color: '#000000'
      }
    },
    apns:{
        payload:{
          aps: {
            sound: 'gears-short.wav'
          }
        }
    }
  }

  return admin.messaging().send(message)

应用程序组件.ts

import { FCM } from 'capacitor-fcm';

const fcm = new FCM();
const { PushNotifications } = Plugins;

initializeApp() {
    this.platform.ready().then(() => {

      PushNotifications.register();

      PushNotifications.addListener('registration', (token: PushNotificationToken) => {
        console.log('token ' + token.value);
        fcm
        .subscribeTo({ topic: 'QMTBC' })
        .then(r => console.log(`subscribed to topic`))
        .catch(err => console.log(err));        
      });

      PushNotifications.addListener('registrationError', (error: any) => {
        console.log('error on register ' + JSON.stringify(error));
      });

      PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) => {
        console.log('notification ' + JSON.stringify(notification));
        this.pushNotificationService.notifications.push(notification);
      });

      PushNotifications.addListener('pushNotificationActionPerformed', (notification: PushNotificationActionPerformed) => {
        console.log('notification ' + JSON.stringify(notification));
        this.pushNotificationService.notifications.push(notification);
      });

      fcm.getToken()
        .then(r => console.log(`Token ${r.token}`))
        .catch(err => console.log(err));
    });
  }

更新:

我尝试如下创建频道。 如果我使用频道,我只会得到默认声音。 如果我指定没有频道或一个不存在的频道,我也会得到默认声音(默认频道)。

云 function:

const message: admin.messaging.Message = {
    notification,
    topic: 'QMTBC',
    android:{
      notification:{
        sound: 'punch.mp3',
        icon: 'push_logo',
        color: '#000000',
        channelId: 'QMTBC'
      }
    }

应用程序组件.ts

const channel: PushNotificationChannel = {
          description: 'QMTBC',
          id : 'QMTBC',
          importance: 5,
          name : 'QMTBC'
        };

        PushNotifications.createChannel(channel).then(channelResult => {
          console.log(channelResult);
          console.log('Channel created');
          // PushNotifications.listChannels().then(channels => {
          //   console.log('Channels');
          //   console.log(channels);
          // });
        }, err => {
          console.log('Error Creating channel');
          console.log(err);
        });
      });

更新 2:

我可以在我的设备上看到我为应用程序创建的频道,它说声音是默认的。 我可以手动将其更改为另一个内置的 android 声音,这很有效。 但我仍然无法使用我的自定义声音。

更新 3:

如果 Android 版本小于 8,则自定义声音有效。仅在模拟器上测试过。

@MadMac 这些天我遇到了同样的问题,在阅读了 FCM 文档和 Capacitor Java 代码后,我明白了。

有必要将可见性设置为 1,将您的文件放在 res/raw 文件夹中。

PushNotifications.createChannel({
            description: 'General Notifications',
            id: 'fcm_default_channel',
            importance: 5,
            lights: true,
            name: 'My notification channel',
            sound: 'notifications.wav',
            vibration: true,
            visibility: 1
        }).then(()=>{
            console.log('push channel created: ');
        }).catch(error =>{
            console.error('push channel error: ', error);
        });

我在我的 firestore 函数中使用这个有效载荷来发送通知

{
            android: {
                notification: {
                    defaultSound: true,
                    notificationCount: 1,
                    sound: 'notifications.wav',
                    channelId: 'fcm_default_channel'
                },
                ttl: 20000,
                collapseKey
            },
            apns: {
                payload: {
                    aps: {
                        badge: 1,
                        sound: 'default'
                    }
                }
            },
            notification: {
                title,
                body: message,
            },
            token: token
        };

这是一个很好的问题,帮助我找到了答案。 所以我在这里发布我的答案。 尝试在创建频道时将通知声音设置为通知频道本身。 我想,根据您的信息,旧的 Android 版本将根据通知负载中的声场播放声音,但在新版本中,您必须将其直接设置为通知通道本身,因为这是现在的控制位置目前打算由谷歌。 我必须卸载并重新安装应用程序才能使此代码更改正常工作,因为我的频道之前已初始化,并且频道在第一次初始化后不会更新。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !notificationChannelsInitialized) {
            val newMessagesChannel = NotificationChannel(NEW_MESSAGES_NOTIFICATION_CHANNEL_ID, "New Messages", NotificationManager.IMPORTANCE_HIGH)

            val notificationSoundUri =
                Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE.toString() + "://" + context.packageName + "/" + R.raw.ns) // ns.wav is my notification sound file in the res/raw folder in Android Studio
            val notificationSoundUriAttributes = AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build()
            newMessagesChannel.setSound(notificationSoundUri, notificationSoundUriAttributes)

            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannels(listOf( newMessagesChannel)) // and other channels
        }

我能够使用react-native-push-notification库( 此处)使其适用于 React Native。 解决的关键是你必须在你的应用程序中创建一个频道。 (我原以为通道是在后端创建的,但那是不对的)。 将 mp3 文件放在我应用程序的android文件夹中的res/raw目录中后,我在 React Native 中添加了以下代码(从上述库中的文档中复制),它起作用了:

import PushNotification, {Importance} from 'react-native-push-notification';
...
  PushNotification.createChannel(
    {
      channelId: "channel-id", // (required)
      channelName: "My channel", // (required)
      channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
      playSound: true, // (optional) default: true
      soundName: "mp3_example", // (optional) See `soundName` parameter of `localNotification` function
      importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
      vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
    },
    (created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
  );

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM