How to bring up list of available notification sounds on Android

后端 未结 5 1715
别跟我提以往
别跟我提以往 2020-12-04 06:45

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

5条回答
  •  攒了一身酷
    2020-12-04 07:10

    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.

提交回复
热议问题