Android通知setSound无效

Dro*_*dOS 15 android uri android-notifications android-6.0-marshmallow

在我的针对API 23+的混合Cordova Android应用中,我想使用自定义声音进行通知.为此,我做了以下工作

  • plugin.xml我声明的应用程序中使用的单个自定义插件的文件中<resource-file src="src/android/res/unysound.mp3" target="res/raw/mysound.mp3" />'.

打开APK作为zip存档我看到mp3文件实际上最终在`res/raw/mysound.mp3'. - 构建通知时,我执行以下操作

    Notification notification = new Notification.Builder(context)
    .setDefaults(0) //turns off ALL defaults
    .setVibrate(vibrate)  /sets to vibrate
    ....
    .setSound(uri).build();
Run Code Online (Sandbox Code Playgroud)

哪里

Uri uri = Uri.parse("android.resource://" + ctxt.getPackageName() + "/raw/mysound.mp3");
Run Code Online (Sandbox Code Playgroud)

这似乎是我在google网站上发现的一些文章中指出的配方,甚至在SO上的其他帖子中也是如此.然而,当我发出通知时,我听不到预期的声音.我可能做错了什么?


下面的答案没有帮助,因为在我的混合Cordova应用程序与自定义插件尝试构建APK的上下文中引发了一个错误的行 class R not known/found...

Ket*_*tel 14

以下代码将帮助您:

String CHANNEL_ID="1234";

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

NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Run Code Online (Sandbox Code Playgroud)

对于API 26+,您需要添加一些额外的代码,如下所示:

NotificationChannel mChannel;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID, Utils.CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            mChannel.setLightColor(Color.GRAY);
            mChannel.enableLights(true);
            mChannel.setDescription(Utils.CHANNEL_SIREN_DESCRIPTION);
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_NOTIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();
            mChannel.setSound(soundUri, audioAttributes);

            if (mNotificationManager != null) {
                mNotificationManager.createNotificationChannel( mChannel );
            }
    }
Run Code Online (Sandbox Code Playgroud)

一般代码:

 NotificationCompat.Builder status = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);     
                      status.setAutoCancel(true)
                            .setWhen(System.currentTimeMillis())
                            .setSmallIcon(R.drawable.logo)
                            //.setOnlyAlertOnce(true)
                            .setContentTitle(getString(R.string.app_name))
                            .setContentText(messageBody)
                            .setVibrate(new long[]{0, 500, 1000})
                            .setDefaults(Notification.DEFAULT_LIGHTS )
                            .setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" +mContext.getPackageName()+"/"+R.raw.apple_ring))
                            .setContentIntent(pendingIntent)
                            .setContent(views);

                    mNotificationManager.notify(major_id, status.build());
Run Code Online (Sandbox Code Playgroud)

mysound是我的铃声,放在res/raw文件夹下.

注意:你必须只放置没有扩展名的铃声名称,如raw/mysound

  • 在 Android Oreo 中,您必须更改频道 ID 才能使更改生效。在 Oreo 版本之前,使用“.setDefaults()”会阻止自定义声音的播放。 (4认同)
  • 我在AudioAttributes中找不到CONTENT_TYPE_NOTIFICATION,因此我忽略了这一点,该解决方案仍然有效。 (2认同)

Dim*_*ski 10

对于API 26+,您需要在通知通道上设置声音:

Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.siren);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel mChannel;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(Utils.CHANNEL_SIREN_ID, Utils.CHANNEL_SIREN_NAME, NotificationManager.IMPORTANCE_HIGH);
            mChannel.setLightColor(Color.GRAY);
            mChannel.enableLights(true);
            mChannel.setDescription(Utils.CHANNEL_SIREN_DESCRIPTION);
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();
            mChannel.setSound(soundUri, audioAttributes);

            if (mNotificationManager != null) {
                mNotificationManager.createNotificationChannel( mChannel );
            }
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Utils.CHANNEL_SIREN_ID)
            .setSmallIcon(R.drawable.ic_stat_maps_local_library)
            .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher))
            .setTicker(title)
            .setContentTitle(contentTitle)
            .setContentText(contentText)
            .setAutoCancel(true)
            .setLights(0xff0000ff, 300, 1000) // blue color
            .setWhen(System.currentTimeMillis())
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            mBuilder.setSound(soundUri);
    }

    int NOTIFICATION_ID = 1; // Causes to update the same notification over and over again.
    if (mNotificationManager != null) {
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,这不是很好,因为如果我们想要一个频道内的不同通知有不同的声音怎么办。 (2认同)

Sid*_*wal 7

  1. 尝试清除数据(或全新安装)
  2. 再试一次

除非您通过全新安装或清除数据手动进行设置,否则设置将在您首次创建通道时进行设置,然后再进行修改。

有关此问题的更多信息,请阅读此处的最佳答案: 即使我未设置声音,Android Oreo通知仍会发出声音。在旧版本上,效果很好

  • 让我感到沮丧的是,无论我添加到“NotificationCompat.Builder”或“NotificationChannel”中的任何声音或振动设置都没有任何区别,直到我清除了应用程序数据并突然开始工作。谢谢,你的回答拯救了我的一天。 (3认同)
  • 我花了好几个小时试图弄清楚为什么没有任何改变,你拯救了我的一天,谢谢 (2认同)

Uma*_*nta 5

您可以在处理通知时调用此方法

    public void playNotificationSound() {
    try {
        Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/notification");
        Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,Android 中有很多事情不应该做,我在过去 4 年中学到了,不要假设任何事情都可以正常工作或已经在 Android 中为您完成,直到您亲眼看到为止。 ..供参考 (7认同)
  • 在这里投票是因为我怀疑使用“ContentResolver”而不是“android.resource://”是一种更适合未来的做事方式。 (3认同)

小智 5

 Notification.Builder builder = new Notification.Builder(context);
    builder.setContentTitle(mTitle);
    builder.setContentText(mContentText);
    builder.setSmallIcon(R.mipmap.ic_launcher);

    builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
    builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
    builder.setDefaults(Notification.DEFAULT_ALL);
Run Code Online (Sandbox Code Playgroud)

用它来处理声音,我希望它能解决您的问题,干杯!