API 26上的通知声音
我在自己的通知中使用了自定义的mp3声音。它可以在API 26以下的所有设备上正常工作。我也试图在Notification Channel上设置声音,但仍然没有工作。它播放默认声音。API 26上的通知声音
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setAutoCancel(true)
.setSmallIcon(R.drawable.icon_push)
.setColor(ContextCompat.getColor(this, R.color.green))
.setContentTitle(title)
.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification))
.setDefaults(Notification.DEFAULT_VIBRATE)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentText(message);
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
channel.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification), audioAttributes);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(1, notification);
我使用了RingtoneManager,它适合我。尝试th代码:
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com/"));
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("Notification title");
builder.setContentText("Notification message.");
builder.setSubText("Url link.");
try {
Uri notification = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.custom_ringtone);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
您可能已经使用默认声音创建了声道。一旦创建了频道,就不能更改。您需要重新安装应用或使用新的频道ID创建频道。
尝试重命名通道,但仍然不工作。 –
小世界:-)感谢Paweł,你为我节省了很多时间! –
要改变重要性,声音,灯光,振动,锁定屏幕或免打扰设置,请卸载应用程序并重新安装以清除频道。请参阅https://developer.android.com/guide/topics/ui/notifiers/notifications.html#ManageChannels,esp标题为“删除通知渠道” – BitByteDog
默认声音覆盖任何声音。
你需要把这个在你的代码:
notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
参考:
仍然没有工作。 –
您必须通过重新安装应用程序或在添加代码之前清除与您的应用程序关联的数据来清除测试通道! –
好的。我今晚再试一次。谢谢。 –
你是否使默认通知声音静音?我也面临同样的问题。我不想在通知NotificationManager.IMPORTANCE_MAX时播放任何声音。你能帮我解决这个问题吗? –