Rodrigo Manguinho
Rodrigo Manguinho

Reputation: 1411

Notification sound on API 26

I have a custom mp3 sound that I use on my notifications. It works fine on all devices below API 26. I tried to set the sound on Notification Channel also, but still no work. It plays the default sound.

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
            .setAutoCancel(true)
            .setSmallIcon(R.drawable.icon_push)
            .setColor(ContextCompat.getColor(this, R.color.green))
            .setContentTitle(title)
            .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification))
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setContentText(message);
        Notification notification = builder.build();
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                    .build();
            channel.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification), audioAttributes);
            notificationManager.createNotificationChannel(channel);
        }
        notificationManager.notify(1, notification);

Upvotes: 34

Views: 27428

Answers (6)

Artem Botnev
Artem Botnev

Reputation: 2427

I've been developing app with similar functionality. And as mentioned Paweł Nadolski we have to recreate channel each time to change ringtone. For this I wrote helper. Hope it can help someone.

@RequiresApi(Build.VERSION_CODES.O)
object ChannelHelper {
    // channel id for 8.0 OS version and higher
    private const val OREO_CHANNEL_ID = "com.ar.app.notifications"
    private const val CHANNEL_ID_PREF = "com.ar.app.notifications_prefs"

    @JvmStatic
    fun createChannel(context: Context, playSound: Boolean, isVibrated: Boolean, uri: Uri) {
        // establish name and importance of channel
        val name = context.getString(R.string.main_channel_name)
        val importance = if (playSound) {
            NotificationManager.IMPORTANCE_DEFAULT
        } else {
            NotificationManager.IMPORTANCE_LOW
        }

        // create channel
        val channelId = OREO_CHANNEL_ID + UUID.randomUUID().toString()
        saveChannelId(context, channelId)

        val channel = NotificationChannel(channelId, name, importance).apply {
            enableLights(true)
            lightColor = Color.GREEN

            lockscreenVisibility = Notification.VISIBILITY_PUBLIC

            // add vibration
            enableVibration(isVibrated)
            vibrationPattern = longArrayOf(0L, 300L, 300L, 300L)

            // add sound
            val attr = AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build()

            setSound(uri, attr)
        }

        // register the channel in the system
        val notificationManager = context.getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
    }

    @JvmStatic
    fun rebuildChannel(context: Context, playSound: Boolean, isVibrated: Boolean, uri: Uri) {
        val notificationManager = context.getSystemService(NOTIFICATION_SERVICE)
                as NotificationManager
        notificationManager.deleteNotificationChannel(
            getChannelId(context) ?: OREO_CHANNEL_ID
        )

        createChannel(context, playSound, isVibrated, uri)
    }

    @JvmStatic
    fun getChannel(context: Context): NotificationChannel? {
        val notificationManager = context.getSystemService(NOTIFICATION_SERVICE)
                as NotificationManager

        return notificationManager.getNotificationChannel(
                getChannelId(context) ?: OREO_CHANNEL_ID
        )
    }

    @JvmStatic
    fun isChannelAlreadyExist(context: Context) = getChannel(context) != null

    @JvmStatic
    fun getChannelId(context: Context) =
            PreferenceManager.getDefaultSharedPreferences(context)
                    .getString(CHANNEL_ID_PREF, OREO_CHANNEL_ID)

    private fun saveChannelId(context: Context, channelId: String) =
            PreferenceManager.getDefaultSharedPreferences(context)
                    .edit()
                    .putString(CHANNEL_ID_PREF, channelId)
                    .apply()
}

Upvotes: 0

Nolesh
Nolesh

Reputation: 7018

In addition to the Faxriddin's answer you can determine when you should to turn off the notification sound by checking the importance of the notification channel and are enabled notifications parameters.

NotificationChannel channel = notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
if(notificationManager.areNotificationsEnabled() && channel.getImportance() != NotificationManager.IMPORTANCE_NONE) {
  try {
     Ringtone r = RingtoneManager.getRingtone(ctx, soundUri);
     r.play();
  } catch (Exception e) { }
}

Upvotes: 0

Towfik Alrazihi
Towfik Alrazihi

Reputation: 546

The default sound overrides any sound.

You need to put this in your code:

notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;

Reference:

Android notifications

Upvotes: 1

Chris
Chris

Reputation: 127

In Oreo you need to create a channel for that. https://developer.android.com/reference/android/app/NotificationChannel.html

Upvotes: 2

Fakhriddin Abdullaev
Fakhriddin Abdullaev

Reputation: 4910

I used RingtoneManager, and it is work for me. Try thius code:

 NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
    builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com/"));
    PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
    builder.setContentTitle("Notification title");
    builder.setContentText("Notification message.");
    builder.setSubText("Url link.");

    try {
        Uri notification = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.custom_ringtone);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }

    NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, builder.build());

Upvotes: 16

Paweł Nadolski
Paweł Nadolski

Reputation: 8473

You may have created the channel originally with default sound. Once channel is created it cannot be changed. You need to either reinstall the app or create channel with new channel ID.

Upvotes: 52

Related Questions