如何为通知添加声音?

Vla*_*mir 24 audio notifications android

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

    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());
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 48

我猜这里的问题是如何用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);
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用的是Notification.Builder,*builder.setDefaults(~Notification.DEFAULT_SOUND);*将执行此操作.感谢@karl提示 (4认同)
  • 我已经通过反复试验回答了我自己的问题:1)mp3工作,wav没有,2)我需要通过构建通知然后执行`n.defaults&= ~Notification.DEFAULT_SOUND来禁用默认声音; ` (2认同)

Ant*_*met 16

要通知你的声音:

Notification notification = new Notification(icon, tickerText, when);
Run Code Online (Sandbox Code Playgroud)

做正常的通知程序

要使用您的通知播放默认声音:

notification.defaults |= Notification.DEFAULT_SOUND;
Run Code Online (Sandbox Code Playgroud)

要使用您的通知播放自定义声音:

notification.sound = Uri.parse("file:///sdcard/notification/notification.mp3");
Run Code Online (Sandbox Code Playgroud)

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