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

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

问题描述:

我有通过云功能使用FCM进行的推送通知.这适用于iOS和Android,并显示适当的图标并在iOS上播放自定义声音.

I have push notifications working using FCM from a cloud function. This works for both iOS and Android and displays the appropriate icon and plays a custom sound on iOS.

除了适用于Android的自定义声音之外,其他所有功能都可以正常工作,只是播放默认声音.

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

I have created a folder and added my sound file to it as follows: android\app\src\main\res\raw\mp3_example.mp3

此mp3长度为27s.我还尝试了.wav和.aiff.

This mp3 is 27s long. I have also tried a .wav and .aiff.

我读到我可能必须为更高版本的Android创建一个推送通知通道,因此它可能与此相关.我尝试创建一个频道并使用云功能中的channelID,它可以正常工作,但是声音只是振动而已.

I read that I may have to create a push notification channel for later versions of Android so it could be related to this. I tried creating a channel and using the channelID from the cloud function and it works but there is no sound just a vibration.

测试设备是运行Android 8的Moto G6. 我在用: 流式细胞仪 Firebase云功能 离子4 电容器类 https://github.com/stewwan/capacitor-fcm

The test device is a Moto G6 running Android 8. I am using: FCM Firebase Cloud Functions Ionic 4 Capacitor https://github.com/stewwan/capacitor-fcm

云功能:

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)

app.component.ts

app.component.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));
    });
  }

更新:

我尝试如下创建频道. 如果使用通道,我只会得到默认声音.如果我未指定任何通道或不存在的通道,我还将获得默认声音(默认通道).

I tried creating a channel as follows. If I use the channel I just get the default sound. If I specific no channel or one that does not exist I also get the default sound (default channel).

云功能:

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

app.component.ts

app.component.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声音,并且可以正常工作.但是我仍然无法使用自定义声音.

I can see the channel I have created for the app on my device and it says the sound is default. I can manually change it to another inbuilt android sound and this works. But I still can't use my custom sound.

更新3:

如果Android版本为&lt ;,则自定义声音有效. 8.仅在模拟器上对此进行测试.

The custom sound works on if the Android version is < 8. Only tested this on an emulator.

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

This was such a good question that helped me find the answer. So I post my answer here. Try setting the sound of the notifications to notification channels themselves at the time when you create the channels. I suppose, based on your info, the old Android versions will play sound according to the sound field in the notification payload, but in the new versions you would have to set it directly to the notification channels themselves since that is where the control is now currently intended to be by Google. I had to uninstall and reinstall the app for this code change to work, because my channels were previously initialized and the channels won't update after the first initialization.

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
        }