How to bring up list of available notification sounds on Android

后端 未结 5 1719
别跟我提以往
别跟我提以往 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:13

    This is the method I use to get a list of notification sounds available in the phone :)

    public Map getNotifications() {
        RingtoneManager manager = new RingtoneManager(this);
        manager.setType(RingtoneManager.TYPE_NOTIFICATION);
        Cursor cursor = manager.getCursor();
    
        Map list = new HashMap<>();
        while (cursor.moveToNext()) {
            String notificationTitle = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
            String notificationUri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
    
            list.put(notificationTitle, notificationUri);
        }
    
        return list;
    }
    

    EDIT: This is for the comment regarding how to set the sound in the NotificationCompat.Builder. This method instead gets the ringtone's ID which is what the phone uses, instead of the human readable TITLE the other method got. Combine the uri and the id, and you have the ringtones location.

    public ArrayList getNotificationSounds() {
        RingtoneManager manager = new RingtoneManager(this);
        manager.setType(RingtoneManager.TYPE_NOTIFICATION);
        Cursor cursor = manager.getCursor();
    
        ArrayList list = new ArrayList<>();
        while (cursor.moveToNext()) {
            String id = cursor.getString(RingtoneManager.ID_COLUMN_INDEX);
            String uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
    
            list.add(uri + "/" + id);
        }
    
        return list;
    }
    

    The above code will return a list of strings like "content://media/internal/audio/media/27".. you can then pass one of these strings as a Uri into the .setSound() like:

    .setSound(Uri.parse("content://media/internal/audio/media/27"))
    

    Hope that was clear enough :)

提交回复
热议问题