【发布时间】:2019-04-29 12:59:40
【问题描述】:
我有一个接收通知的应用程序,一切正常。但是,自定义声音和振动不起作用。我正在 Android 9 pie 上测试它。
Uri sound = Uri.parse("android.resource://" +getApplicationContext().getPackageName()+ "/" +R.raw.siren); //ContentResolver.SCHEME_ANDROID_RESOURCE +
String NOTIFICATION_CHANNEL_ID = "com.example.bantay.bantay.test";
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setWhen(System.currentTimeMillis());
notificationBuilder.setSmallIcon(R.drawable.marikinalogo);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(body);
notificationBuilder.setSound(sound);
notificationBuilder.setVibrate(new long[]{500, 1000, 500, 1000});
if(title.toLowerCase().contains("1")){
notificationBuilder.setContentIntent(pendingIntent);
}
else{
notificationBuilder.setContentIntent(pendingIntent3);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{500, 1000, 500, 1000});
notificationChannel.setSound(sound, audioAttributes);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(0, notificationBuilder.build());
我不知道我的错误。 NOTIFICATION_CHANNEL_ID 是否会影响通知的行为?
【问题讨论】:
-
我记不太清了,但是在设置声音和振动之前尝试执行 setDefaults()。是的,通知通道设置会影响 Android O。默认情况下,您可以为发布到该通道的所有通知指定通知声音。但是您可以在每个通知中覆盖声音。
-
@mnp343 我尝试添加 setDefaults(Notification.DEFAULT_ALL),但还是不行?
-
似乎您缺少设置优先级。Android O 及以上版本为 NotificationManager.IMPORTANCE_HIGH,以下为 Notification.PRIORITY_MAX。愿这行得通。
-
else setSound(Settings.System.DEFAULT_NOTIFICATION_URI) 和 setDefaults(Notification.DEFAULT_VIBRATE) 在设置声音之前。我不确定,但这可能有效。
-
@mnp343 设置默认值并添加 Notification.PRIORITY_MAX 对我有用,谢谢!
标签: android android-notifications android-notification-bar