Custom sound for NotificationChannel for Android 11 not working

2.4k Views Asked by At

I have push notifications with custom sounds working until android 10. Since Android 11 the sound attached to the notification channel stopped playing when the notification is presented as drop down style. It works when it is presented as full screen activity.

Here is the example source code how the notification channel is created

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

    String channelId = "media_playback_channel_v_01_1_sound"
    String channelName = "Channel High"
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("My custom sound");
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

        AudioAttributes.Builder builder = new AudioAttributes.Builder();
        builder.setUsage(AudioAttributes.USAGE_NOTIFICATION);
    String basePath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.alarm_sound);
    Uri alarmSound = Uri.parse(basePath);
        channel.setSound(alarmSound, builder.build());

        channel.enableVibration(true);
        channel.enableLights(true);
        channel.setLightColor(Color.RED);
    }
}

I use the notification channel above and fire the notification as follow:

private void fireNotification(Context context) {
    String channelId = "media_playback_channel_v_01_1_sound"
        NotificationChannel channel = getManager().getNotificationChannel(channelId);


        PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(context, 100,
                fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        String contentText = getString(R.string.call_notification_incoming_from, from);

        Bundle args = new Bundle();
        args.putInt(CallActivity.INTENT_CALL_NOTIFICATION_ID, ActiveCall.ANDROID_10_PUSH_CALL_NTFN_ID);
        args.putBoolean(CallActivity.INTENT_FROM_CALL_NOTIFICATION, true);
        args.putString(CallActivity.INTENT_NOTIFICATION_CALL_ID, fullScreenIntent.getStringExtra(CallActivity.INTENT_NOTIFICATION_CALL_ID));

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, type)
                        .setSmallIcon(iconRes)
                        .setContentTitle(getString(R.string.app_name))
                        .setContentText(contentText)
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setCategory(NotificationCompat.CATEGORY_CALL)
                        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                        .setOngoing(true)
                        .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_ALL)
                        .setTimeoutAfter(Consts.MINUTE)
                        .addExtras(args);

    notificationBuilder.addAction(
        R.drawable.ic_accept_call,
                getString(R.string.call_notification_incoming_answer),
                answerPendingIntent);
        notificationBuilder.addAction(
                        R.drawable.ic_decline_bttn,
                        getString(R.string.call_notification_incoming_reject),
                        rejectPendingIntent
                );
        notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true);

    // Build
        Notification notification = notificationBuilder.build();
    notification.sound = notificationSoundUri;
        notification.flags |= (Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_INSISTENT Notification.FLAG_NO_CLEAR);
        notification.ledARGB = Color.RED;
        notification.ledOnMS = 300;
        notification.ledOffMS = 1000;

    // Notify
        NotificationManager notificationManager = getManager();
        notificationManager.notify(id, notification);
}

Note that the same code plays the sound in Android 10, while it does not on Android 11.

2

There are 2 best solutions below

2
On

I am also stuck for android 11 but I tried different channel name and do not channel channel ID.

This solution is working for me in every android version 11 devices.

Please try this and let me know if this will not working for you.

public void showNotification(String title, String message) {
        count++;
        Intent intent = new Intent(this, HomePageActivity.class);
        String channel_id = "notification_channel";
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.coin);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channel_id)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setAutoCancel(true)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
                .setOnlyAlertOnce(true)
                .setSound(soundUri)
                .setContentIntent(pendingIntent);
        builder.setNumber(count);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            builder = builder.setContent(getCustomDesign(title, message));
        } else {
            builder = builder.setContentTitle(title).setContentText(message).setSmallIcon(R.mipmap.ic_launcher_round);
        }
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(channel_id, "DIFFRENT_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH); // Here I tried put different channel name.
            notificationChannel.setShowBadge(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                notificationChannel.canBubble();
            }
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();

            notificationChannel.canShowBadge();
            notificationChannel.enableVibration(true);
            notificationChannel.setSound(soundUri, audioAttributes);
            notificationManager.createNotificationChannel(notificationChannel);
            notificationManager.notify(0, builder.build());
        }
    }
0
On

Finally, after researching a lot, I found a solution. All you need is this:-

  • While Creating Notification Channel, create different channels for Silent Notification, Custom Sound Notification, etc.

      // The custom sound file name you want
      val soundName = "beep"
      val soundUri = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://${packageName}/raw/${soundName}")
    
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          val importance = NotificationManager.IMPORTANCE_HIGH
          val audioAttributes = AudioAttributes.Builder()
              .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
              .setUsage(AudioAttributes.USAGE_NOTIFICATION)
              .build()
    
          // Here The CHANNEL_ID is the main thing for creating a channel. Use this same CHANNEL_ID in Notification Builder Also.
          val channel = NotificationChannel(CHANNEL_ID, getString(R.string.app_name), importance).apply {
              description = getString(R.string.app_name)
              setSound(null, audioAttributes) // Give Null if you want silent notification
              // setSound(soundUri, audioAttributes)
          }
          notificationManager.createNotificationChannel(channel)
      }
    

Notification Builder:-

        // Here The CHANNEL_ID needs to be same like the above created channel id. Because it defines how notification sound come.
    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(smallIcon)

    with(notificationManager) {
        notify(notificationId, builder.build())
    }