android 8.0系统开始加入了一个新功能,就是可以生成前台通知渠道,用于自定义声音,震动等快捷操作,如果想一直常驻于通知栏,在自定义的Service中调用 startForeground(notifyID, notification);
就可以了,代码例子如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = "imservice";
String name = "前台通知渠道测试";
String description = "测试内容";
int importance = 0;
NotificationChannel mChannel = new NotificationChannel(id, (CharSequence) name, importance);
mChannel.setSound((Uri) null, (AudioAttributes) null);
mChannel.setDescription(description);
notificationManager.createNotificationChannel(mChannel);
int notifyID = 999;
Notification notification = (new Notification.Builder((Context) this))
.setContentTitle((CharSequence) name)
.setContentText((CharSequence) description)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_channel_1))
.setSmallIcon(R.mipmap.ic_channel)
// .setContentIntent(this.getIntent())
.setChannelId(id).build();
this.startForeground(notifyID, notification);
}
效果图如下:
如果已经打开了这个常驻通知渠道,又想在其他地方关掉,代码如下:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
// 删除之前im中ImService中生成的渠道
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.deleteNotificationChannel("imservice");
}
还发现个神奇的地方,设置 NotificationChannel的importance,当设置比较较高级别,就会自动弹出横幅通知,代码如下:
NotificationChannel channel = new NotificationChannel(channelId,
"通知渠道测试",
NotificationManager.IMPORTANCE_HIGH);
好了,又可以愉快玩耍了