当尝试在应用程序中生成通知时,在装有Android 8.0.0(API 26)的Samsung s9上进行了测试,我无法为其提供自定义声音。只是为了测试,我会发出如下声音:
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
然后我为第一个通知定义并创建一次渠道,如下所示。
int importance = NotificationManager.IMPORTANCE_MAX;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification channel", importance);
channel.setDescription("Channel for current notifications");
channel.setVibrationPattern(new long[] {100, 200, 100, 200});
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(sound, audioAttributes);
channel.setLightColor(Color.BLUE);
channel.enableLights(true);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
mNotificationManager.createNotificationChannel(channel);
然后我使用>
为> = API 26构建通知 notificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(notificationMessage)
.setOngoing(true)
.setVibrate(vibrationPattern)
.setSound(sound)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.logo))
.setSmallIcon(R.drawable.logo)
.setContentIntent(PendingIntent.getActivity(mContext, 0, activityPendingIntent, PendingIntent.FLAG_CANCEL_CURRENT))
.setAutoCancel(false)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(notificationMessage));
或对于API <26,不推荐使用的方式:
notificationBuilder = new NotificationCompat.Builder(mContext)
.setVibrate(vibrationPattern)
.setSound(sound)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(notificationMessage)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setOngoing(true)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.logo))
.setSmallIcon(R.drawable.logo)
.setContentIntent(PendingIntent.getActivity(mContext, 0, activityPendingIntent, PendingIntent.FLAG_CANCEL_CURRENT))
.setAutoCancel(false)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(notificationMessage));
在较旧的手机(在我的情况下为具有Android 5.1.1 API 22的Samsung J3)上运行它时,看到通知时我确实收到了ALARM声音,并且如果我更改了sound
对象,我会得到新的声音用于通知。但是,在更新的具有Android 8.0.0 API 26的Samsung S9上,我始终会收到手机的默认通知声音。
我已经测试过完全重新安装该应用程序以清除频道,所以我没有任何旧设置。不过,如果我进入设置->应用程序->我的应用程序->通知,然后单击我可以选择声音的频道,它会显示“通知的默认声音”,并且永远不会改变。
我应该怎么做才能使通知通知我的较新设备的选择?还是仅仅有些电话让我不能这样做?
编辑1 在我将AudioAttributes更改为
后,它似乎可以正常工作AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();