Android 通知 setSound 不工作

Android notification setSound is not working

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

打开 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();

其中

Uri uri = Uri.parse("android.resource://" + ctxt.getPackageName() + "/raw/mysound.mp3");

这似乎是我在谷歌搜索上什至在 SO 的其他线程中找到的许多文章中指出的方法。然而,当我发出通知时,我没有听到预期的声音。我可能做错了什么?


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

您正在访问资源子文件夹中的声音

将您的 uri 源更改为

Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.siren);

对于默认声音,使用:

notification.defaults |= Notification.DEFAULT_SOUND;

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

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

我不确定,但我认为问题是你做错了 "/raw/mysound.mp3 :

Uri uri = Uri.parse("android.resource://" + ctxt.getPackageName() + "/raw/mysound.mp3");

首先在清单中添加权限:uses-permission android:name="android.permission.VIBRATE" /> 然后你可以设置默认声音:-

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);

和振动:

mBuilder.setVibrate(new long[] { 1000, 1000});

对于自定义声音,将 mp3 文件放在这个路径上:Res\raw\sound.mp3 然后

Notification notification = builder.build();
 notification.sound = Uri.parse("android.resource://"
        + context.getPackageName() + "/" + R.raw.sound);

用它来设置声音

Uri defaultSoundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + mContext.getPackageName() + "/raw/mysound");


NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(mContext)
                        .setContentIntent(mainPIntent)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
                        .setContentTitle("" + title)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentText("" + body);

        NotificationManager mNotificationManager =
                (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(title, NOTIFICATION_ID, mBuilder.build());

以下代码将帮助您:

 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); 
    
  //For API 26+ you need to put some additional code like below:
    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_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                        .build();
                mChannel.setSound(soundUri, audioAttributes);
    
                if (mNotificationManager != null) {
                    mNotificationManager.createNotificationChannel( mChannel );
                }
        }

   //General code:
     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());

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

注意:你只需要输入没有扩展名的铃声名称,如raw/mysound

注意:在Android Oreo 中,您必须更改频道 ID 才能使更改生效。在 Oreo 版本之前,使用“.setDefaults()”会阻止播放自定义声音。

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

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

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

这些设置是在您第一次创建频道时设置的,除非您通过全新安装或清除数据手动进行修改,否则不会进行修改。

有关这方面的更多信息,请阅读此处的最佳答案:

对于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());
    }