Using alarm sound instead of default notification sound in Android

1k views Asked by At

I'm trying to send an alarm like notification that stays on the screen and plays the alarm sound until it's closed.

I tried setting the alarm sound on the notification channel and on the notification itself but nothing seems to work, the notification always plays the default notification sound.

val name = "name"
        val descriptionText = "desc"
        val importance = NotificationManager.IMPORTANCE_HIGH
        val channel = NotificationChannel("id", name, importance).apply {
            description = descriptionText
        }


        val notificationManager: NotificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)


        val audioAttributes = AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build()

        channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), audioAttributes)

        val builder = NotificationCompat.Builder(context, "id")
            .setSmallIcon(R.drawable.ic_android_black_24dp)
            .setContentTitle("textTitle")
            .setContentText("textContent")
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
            .setPriority(NotificationCompat.PRIORITY_MAX)
            //.setCategory(NotificationCompat.CATEGORY_ALARM)
            .setFullScreenIntent(fullScreenPendingIntent, true)
            .addAction(1, "a", closeButtonPendingIntent)



        with(NotificationManagerCompat.from(context)) {
            notify(0, builder.build())
        }
1

There are 1 answers

7
Richard Onslow Roper On

There's no way to make the notification "sound" like the alarm that will satisfy your use-case. You could use the RingtoneManager API to retrieve the default alarm sound, and use the setSound method of the "builder" (not the notification channel) to notify with that sound, but even then, it will be just one iteration of a short sound sequence, then it'll stop. Notifications Builders are not meant to be used for playing a constant sound for the user. They are just single-shot notifications.

For an alarms app, you'll need a MediaPlayer alongside the notification builder. You'd likely want to keep the notification itself silent, and use the sound retrieved from the RingtoneManager to make a sound using the mediaplayer instance with isLooping set to true.

The ringtones cannot be expected to last indefinitely. They are short sequences of sound. You are the one who has to play it until it needs to be stopped.

Sample implementation:

MediaPlayer().apply {
  dataSource = /*Add Default Ringtone here*/
  isLooping = true
  start()
}