Notification sound from URI parse does not work

前端 未结 3 586
深忆病人
深忆病人 2021-01-15 19:23

There are at least 7 questions on Stackoverflow related to this, I have tried every single suggestion and solution multiple times and none of them have worked. Here is my la

3条回答
  •  伪装坚强ぢ
    2021-01-15 19:42

    I was having a similar problem while testing on API 23. While I do not know the cause of the problem, I did manage to find a workaround that got the job done.


    In one of Google's examples, a notification is constructed thusly:

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    
    // Define the notification settings.
    builder.setSmallIcon(R.drawable.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_launcher))
            .setColor(Color.RED)
            .setContentTitle(notificationDetails)
            .setContentText(getString(R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);
    
    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);
    
    // Get an instance of the Notification manager
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
    // Issue the notification
    mNotificationManager.notify(0, builder.build());
    

    Notice the class NotificationCompat.Builder. For some reason which is beyond me, this did not play any sound other than the default one. In other words, only this worked:

    // Define sound URI
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // Default
    ...
    builder.setSound(soundUri); //Set the sound to play
    

    But this didn't:

    Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + 
                               getPackageName() + "/" + R.raw.name_of_sound);
    

    After simply replacing the builder class with Notification.Builder (available for API >= 11) the "this didn't" section above started working as expected.

    Conclusion: use this if you're willing to sacrifice (or are not interested in) compatibility with API < 11.

提交回复
热议问题