1. 前言
最近需要实现一个不会打开呼吸灯、不会震动和没声音的通知,查找了很多资料,但没有一个写得完整的。东凑凑,西凑凑,自己摸索了几个小时,找到了一种较可靠的方式。
2. 解决方案
这种方案兼容到了Android 8.0,三星、华为和小米手机都有效果。
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setContentText("有待办消息未读")
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
.setVibrate(new long[]{0})
.setSound(null);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("to-do", "待办消息",
NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(false);
channel.enableVibration(false);
channel.setVibrationPattern(new long[]{0});
channel.setSound(null, null);
notificationManager.createNotificationChannel(channel);
builder.setChannelId("to-do");
}
Notification notification = builder.build();
notificationManager.notify(0, notification);