我也遇到了通知必须发出声音的问题,当应用程序在前台时一切正常,但是当应用程序在后台时,声音就没有发出。
通知是服务端通过FCM发送的,即服务端挂载通知的JSON发送给FCM,FCM再将通知发送给应用。即使我放了声音标签,声音也不会在背景中发出。
即使放置声音标签也不起作用。
经过大量搜索,我在 github 论坛上找到了解决方案。然后我注意到我的案例有两个问题:
1 - 缺少发送 channel_id 标签,这对于在 API 级别 26+ 中工作很重要
2 - 在 Android 应用程序中,对于这种直接从服务器发送通知的特定情况,我必须提前配置通道 ID,因此在我的主 Activity 中我必须配置通道以便 Android 知道什么通知到达时执行。
在服务器发送的 JSON 中:
{
"title": string,
"body": string,
"icon": string,
"color": string,
"sound": mysound,
"channel_id": videocall,
//More stuff here ...
}
在您的主要活动中:
@Background
void createChannel(){
Uri sound = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.app_note_call);
NotificationChannel mChannel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel = new NotificationChannel("videocall", "VIDEO CALL", NotificationManager.IMPORTANCE_HIGH);
mChannel.setLightColor(Color.GRAY);
mChannel.enableLights(true);
mChannel.setDescription("VIDEO CALL");
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
mChannel.setSound(sound, audioAttributes);
NotificationManager notificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(mChannel);
}
}
这终于解决了我的问题,我希望它可以帮助别人不要像我一样浪费 2 天。我不知道我在代码中输入的所有内容是否有必要,但这就是方式。我也没有找到 github 论坛链接来感谢答案,因为我所做的与那里发布的相同。