如何在Android 8.0中设置带有自定义声音的通知?

时间:2018-10-11 09:50:49

标签: android push-notification android-8.0-oreo

我尝试设置自定义通知声音,该声音在Oreo(8.0)设备下可以正常工作,但在Oreo设备中,它不会触发自定义声音,始终会触发默认声音。有人可以帮忙吗?

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Notification.Builder notificationBuilder =
                    new Notification.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(title)
                            .setContentText(content)
                            .setAutoCancel(true)
                            //.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
                            //.setSound(defaultSoundUri)
                            .setContentIntent(pendingIntent);

            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
            // Configure the notification channel.
            AudioAttributes att = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                    .build();
            notificationChannel.setSound(defaultSoundUri, att);
            notificationChannel.setDescription(content);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

        } else {
            NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(title)
                            .setContentText(content)
                            .setAutoCancel(true)
                            .setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
                            .setSound(defaultSoundUri)
                            .setContentIntent(pendingIntent);

            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

        }

1 个答案:

答案 0 :(得分:0)

如果您使用的是Oreo下的Android版本,则只需将MY_SOUND_NOTIFICATION.mp3添加到名为 raw 的文件夹中的资源,然后开始对您的类,但是由于您使用的是Oreo或更高版本,因此您需要检查SDK_VERSION才能使用setSound

中称为NotificationChannel的方法

由于您没有发布代码以进行更正,因此我不会发布任何代码。如果您发布一些代码,我们将很乐意为您