Android Notification Builder不会播放自定义声音

时间:2016-09-28 21:09:50

标签: android android-studio audio push-notification android-notifications

我发布了用于检索邮件的代码并显示来自firebase的通知。我收到带有正确文本和标题的通知,但此通知是静默的。即使我设置默认声音或自定义声音。 我该如何播放正确的声音?

公共类NotificationMessagingService扩展了FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d("sb.fbv", "NotificationMessaginService.onmessageReceived");
    String title = remoteMessage.getNotification().getTitle();
    String subText = remoteMessage.getNotification().getBody();
    String message = remoteMessage.getData().get("subtext");

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
    nb.setContentTitle(title);
    nb.setSubText(message);
    nb.setContentText(subText);
    nb.setSmallIcon(R.drawable.notificavedelago);
    nb.setAutoCancel(true);
    nb.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
    nb.setLights(Color.BLUE, 3000, 3000);

    //SOUND DEFAULT
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    nb.setSound(alarmSound);

    //CUSTOM SOUND
    //Uri customSound= Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound);
    //nb.setSound(customSound);

    nb.setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, nb.build());

}

}

1 个答案:

答案 0 :(得分:0)

要在通知构建器中设置自定义警报声音,请执行以下操作:

int soundResId = R.raw.myCustomSoundResource;
Uri soundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + soundResId);
nb.setSound(soundUri, AudioManager.STREAM_ALARM);

使用res/raw/myCustomSoundResource.ogg等文件的资源ID号。它可以在any of these supported file formats