Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

android - How to add sound to notification?

How do you add sound to a notification created by NotificationCompat.Builder? I created a raw folder in res and added the sound there. So how do I now add it to notification? This is my Notification code

    int NOTIFY_ID=100;
    Intent notificationIntent = new Intent(this, Notification.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.notification)
            .setContentTitle("Warning")
            .setContentText("Help!")

    NotificationManager mgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mgr.notify(NOTIFY_ID, mBuilder.build());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm guessing the problem here is how to reference the sound with a Uri, as there is an obvious method in the NotificationCompat.Builder class - setSound(Uri soundUri).

To access your raw resources you need to create the Uri as follows:

android.resource://[PACKAGE_NAME]/[RESOURCE_ID]

So the code could end up looking like that:

Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
mBuilder.setSound(sound);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...