25

如何为 NotificationCompat.Builder 创建的通知添加声音?我在 res 中创建了一个 raw 文件夹并在那里添加了声音。那么我现在如何将它添加到通知中呢?这是我的通知代码

    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());
4

3 回答 3

49

我猜这里的问题是如何用 a 引用声音Uri,因为类中有一个明显的方法NotificationCompat.Builder- setSound(Uri soundUri)

要访问您的raw资源,您需要创建Uri以下内容:

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

所以代码最终可能看起来像这样:

Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
mBuilder.setSound(sound);
于 2012-12-26T17:33:29.030 回答
16

使用通知播放声音:

Notification notification = new Notification(icon, tickerText, when);

做正常的通知程序

要在通知中播放默认声音:

notification.defaults |= Notification.DEFAULT_SOUND;

要在通知中播放自定义声音:

notification.sound = Uri.parse("file:///sdcard/notification/notification.mp3");

然后只需使用通知管理器发送通知。如果同时使用这两个语句,应用程序将默认使用默认声音。

于 2012-12-26T17:35:44.707 回答
0

对于 Android 8 (Oreo) 及更高版本,您应该使用Notification Channel来显示通知,如果您没有禁用它,它们会自动发出声音。

对于较旧的设备,您可以使用 Notification Builder 设置声音。您可以使用Notification.Builder.setSound()设置自定义声音,也可以使用

Notification.Builder.setDefaults(NotificationCompat.DEFAULT_SOUND) 设置默认声音。

振动和灯光也有默认设置

于 2019-03-23T00:25:17.973 回答