I\'m creating notifications in my Android application, and would like to have an option in my preferences to set what sound is used for the notification. I know that in the
Here's another approach (in Kotlin), build from other answers in this question, that allows you to specify the name of the tone, and then play it:
fun playErrorTone(activity: Activity, context: Context, notificationName: String = "Betelgeuse") {
val notifications = getNotificationSounds(activity)
try {
val tone = notifications.getValue(notificationName)
val errorTone = RingtoneManager.getRingtone(context, Uri.parse(tone))
errorTone.play()
} catch (e: NoSuchElementException) {
try {
// If sound not found, default to first one in list
val errorTone = RingtoneManager.getRingtone(context, Uri.parse(notifications.values.first()))
errorTone.play()
} catch (e: NoSuchElementException) {
Timber.d("NO NOTIFICATION SOUNDS FOUND")
}
}
}
private fun getNotificationSounds(activity: Activity): HashMap {
val manager = RingtoneManager(activity)
manager.setType(RingtoneManager.TYPE_NOTIFICATION)
val cursor = manager.cursor
val list = HashMap()
while (cursor.moveToNext()) {
val id = cursor.getString(RingtoneManager.ID_COLUMN_INDEX)
val uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX)
val title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX)
list.set(title, "$uri/$id")
}
return list
}
It can probably take some refactoring and optimization, but you should get the idea.