Android 通知设置声音不起作用

问题描述 投票:0回答:9

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

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

以 zip 存档形式打开 APK,我发现 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");

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


下面的答案没有帮助,因为在我的混合 Cordova 应用程序的上下文中,尝试构建 APK 的自定义插件会引发类似

class R not known/found...

的错误
android uri android-notifications android-6.0-marshmallow
9个回答
56
投票

下面的代码可以帮助你:

 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()”会阻止自定义声音的播放。


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

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

有关这方面的更多信息,请阅读此处的最佳答案: 即使我没有设置声音,Android Oreo 通知也会不断发出声音。在旧版本上,完美运行


22
投票

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

14
投票

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

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

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

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


1
投票

用它来设置声音

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

0
投票

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

将 uri 的来源更改为

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

对于默认声音,请使用:

notification.defaults |= Notification.DEFAULT_SOUND;

0
投票

我不确定,但我认为问题是你做错了方法

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

0
投票

这在另一个答案的评论中提到过,但我认为值得重复。

setSound()
enableVibration()
enableLights()
- 这些选项均不适用于 现有 通道。即使你尝试聪明地调用
deleteNotificationChannel
并重新创建它 - 它永远不会起作用。您必须创建一个新的通知通道 ID,然后您的所有更改才会生效。

© www.soinside.com 2019 - 2024. All rights reserved.