我在将一个频道的通知声音更新到Android Oreo时遇到了一些麻烦。我知道用户可以通过打开应用程序通知屏幕手动设置声音,但我想通过将RingtonePreference用于默认设置活动(用户能够从我的应用程序内的活动中获取通知声音)以编程方式执行此操作。
问题是,触发到应用程序的第一个通知从PreferenceManager.getDefaultSharedPreferences()中获取默认声音值,并在手动将其更改为其他媒体(使用RingtonePreference屏幕)后,它仍将播放最初在该通道上创建的声音,而不是用户选择的新的。
我不明白为什么NotificationChannel声音没有根据新的声音值更新,因为我正在做这样的事情
NotificationChannel mChannel = new NotificationChannel(id, title, importance);
mChannel.setSound(ringtoneUri, audioAttributes);
以下是完整代码:
public static void sendNotification(Context context, NotificationType notificationType) {
String id = "channel_1"; // default_channel_id
String title = "Doppler Channel"; // Default Channel
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Uri ringtoneUri = Uri.parse(preferences.getString("notifications_new_message_ringtone", "DEFAULT_RINGTONE_URI"));
boolean isNotificationSticky = !Boolean.parseBoolean(preferences.getAll().get("stickyNotification").toString());
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationManager notifManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
mChannel = new NotificationChannel(id, title, importance);
mChannel.setSound(ringtoneUri, audioAttributes);
notifManager.createNotificationChannel(mChannel);
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder .setSmallIcon(notificationType.getNotificationIcon())
.setContentTitle(notificationType.getNotificationContent())
.setSubText(notificationType.getNotificationTitle())
.setOnlyAlertOnce(true)
.setOngoing(isNotificationSticky)
.setAutoCancel(true)
.setSound(ringtoneUri)
.setColor(notificationType.getNotificationColor())
.setContentIntent(pendingIntent);
}
Notification notification = builder.build();
notifManager.notify(1, notification);
}
我能够更新声音的唯一方法是每次触发通知时给通道ID一个随机值UUID.randomUUID().toString()
,但是当用户手动检查应用程序通知屏幕时,这会导致大量垃圾。
对此的暗示将非常感激。
非常感谢!
我不明白为什么NotificationChannel声音没有根据新的声音值更新
在大多数情况下,NotificationChannel
是一次性写入API。创建后,您无法修改其大部分特征。
但我希望通过将RingtonePreference用于默认的“设置”活动来以编程方式执行此操作
我建议您从应用中删除此功能,或仅在Android 7.1和旧设备上提供此功能。