Custom Notification Sound not working in Oreo

2020-02-08 15:34发布

问题:

Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);
            mBuilder.setSound(sound);

I had copied the mp3 (notification_mp3.mp3) file into the raw folder in the res folder. When the notification is triggered it produces given mp3 sound upto Android Nougat but default sound in Android Oreo. I had referred many sites but nothing worked on Android Oreo. I didn't find any changes in Android Docs regarding notification sound in Android O & above. What changes should be done to make this code working in Android O too?

回答1:

To set a sound to notifications in Oreo, you must set sound on NotificationChannel and not on Notification Builder itself. You can do this as follows

Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        NotificationChannel mChannel = new NotificationChannel("YOUR_CHANNEL_ID",
            "YOUR CHANNEL NAME",
            NotificationManager.IMPORTANCE_DEFAULT)

        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, 
                context.getString(R.string.app_name),
                NotificationManager.IMPORTANCE_HIGH);

        // Configure the notification channel.
        mChannel.setDescription(msg);
        mChannel.enableLights(true);
        mChannel.enableVibration(true);
        mChannel.setSound(sound, attributes); // This is IMPORTANT


        if (mNotificationManager != null)
            mNotificationManager.createNotificationChannel(mChannel);
    }

This will set a custom sound to your notifications. But if the app is being updated and the notification channel is used before, it won't be updated. i.e. you need to create a different channel and set sound to it to make it work. But this will show multiple channels in the notifications section of app info of your app. If you are setting sound to an entirely new channel that is fine, but if you want the channel being used before, you have to delete the existing channel and recreate the channel. To do that you can do something like that before creating channel

if (mNotificationManager != null) {
            List<NotificationChannel> channelList = mNotificationManager.getNotificationChannels();

            for (int i = 0; channelList != null && i < channelList.size(); i++) {
                mNotificationManager.deleteNotificationChannel(channelList.get(i).getId());
            }
        }


回答2:

Create a channel (I use this method in Application.clss to create the channel )

  public void initChannels(Context context) {
    if (Build.VERSION.SDK_INT < 26) {
        return;
    }
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel channel = new NotificationChannel("default"/*CHANNEL ID*/,
            "CHANNEL_NAME",
            NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Channel description");
    assert notificationManager != null;
    notificationManager.createNotificationChannel(channel);
}

And use this channel default while creating instance of NotificationCompat

 .... notificationBuilder = new NotificationCompat.Builder(this,"default") ....


回答3:

Android O comes with NotificationChannel use that instead

 int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            assert mNotificationManager != null;
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            mNotificationManager.createNotificationChannel(notificationChannel);


回答4:

try this:

/**
 * show notification
 *
 * @param message
 */
private static void showNotification(RemoteMessage message, Context baseContext) {
    Context context = baseContext.getApplicationContext();
    NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context.getApplicationContext());
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, null)
            .setSmallIcon(R.drawable.ic_logo_xxxdpi)
            .setContentTitle(message.getData().get(TITLE))
            .setContentText(message.getData().get(BODY))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            .setVibrate(new long[]{500, 500})
            .setLights(Color.RED, 3000, 3000)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setContentIntent(getPendingIntent(context, message));
    managerCompat.notify(getRandom(), builder.build());
}