Java 奥利奥;饼图通知
问题:我的应用程序需要可由用户自定义的通知。为通知设置不同的声音、标题和文本 问题:我知道通知通道只设置了一次,不能修改,所以我想我可以只使用变量,但是即使使用变量,一旦我选择了一个声音,它仍然是那个声音,根本不能更改。我能想到的唯一解决办法是,每次有东西改变时,都要换一个新的频道,这看起来很愚蠢。 当然还有别的办法 此外,在Android Pie上,通知声音根本不起作用,我不知道为什么Java 奥利奥;饼图通知,java,android,Java,Android,问题:我的应用程序需要可由用户自定义的通知。为通知设置不同的声音、标题和文本 问题:我知道通知通道只设置了一次,不能修改,所以我想我可以只使用变量,但是即使使用变量,一旦我选择了一个声音,它仍然是那个声音,根本不能更改。我能想到的唯一解决办法是,每次有东西改变时,都要换一个新的频道,这看起来很愚蠢。 当然还有别的办法 此外,在Android Pie上,通知声音根本不起作用,我不知道为什么 Uri soundUri = Uri.parse(notificationSound); Notificat
Uri soundUri = Uri.parse(notificationSound);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(customTextTitle)
.setContentText(customTextBody)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if(soundUri != null){
// Changing Default mode of notification
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
// Creating Channel
NotificationChannel notificationChannel = new NotificationChannel("CH_ID","Testing_Audio",NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(soundUri,audioAttributes);
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
mNotificationManager.notify(0, notificationBuilder.build());
}
您执行了错误的设置,设置如下所示
notificationBuilder.setSound(soundUri,audioAttributes);
我已经解决了这个问题,尽管是以一种令人讨厌的方式:(如果>=Oreo,我最终将声音设置为null,并使用媒体播放器播放通知声音,同时将audioStream设置为STREAM_通知。显然这并不理想,但由于它是通知而不是警报,音频不应超过设置的时间,以便在onReceive期间执行任务 我能看到的唯一问题是,如果用户决定静音通知/调整手机上的频道。静音显然不会影响媒体播放器播放的声音,而且很可能显示为没有声音,这是不幸的
try {
mp.setDataSource(context.getApplicationContext(), soundUri);
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mp.prepare();
mp.start();
} catch (Exception e) {
//exception caught in the end zone
}
对于其他有此问题的人,我在这里找到了一篇非常棒的帖子,这篇帖子与我的解决方案相同,但更强大、更深入。多个频道应该支持多个声音。根据不同的声音创建不同的频道。谢谢,因为用户可能有太多不同的声音,我每次都感觉像是一个新频道可能会变得非常过度。(对于可能使用它们的用户,可能看起来有问题)频道的想法是让用户控制通知。您只能有有限的通知类型。我尝试了这一点,但builder.setSound不允许我添加音频属性,因为它要求int。声音的工作方式是另一种,但它只是作为特定的声音被卡住,用户没有自定义。。