常驻通知栏
不废话,上代码
//创建一个通知管理器
NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 获取Notification实例
Notification notification=new NotificationCompat.Builder(this,channelId)
.setContentTitle("title")
.setContentText("content")
.setWhen(System.currentTimeMillis())
// .setAutoCancel(false) 点击通知栏后是否消失
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon))
// .setCustomContentView(remoteView) // 设置自定义的RemoteView,需要API最低为24
.setSmallIcon( R.mipmap.instant)
// 设置点击通知栏后跳转地址
.setContentIntent( PendingIntent.getActivity(this, 0, new Intent(this, SecondActivity.class), 0))
.build();
// 添加渠道
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel(channelId, "subscribeName", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("description");
notificationManager.createNotificationChannel(channel);
}
// 设置常驻 Flag
notification.flags = Notification.FLAG_ONGOING_EVENT;
//展示通知栏
notificationManager.notify(notificationId,notification);
展示效果如下
注意
在8.0以下手机是不用添加渠道的,但在之上不添加渠道不展示通知栏,9.0手机不设置setDescription()依旧不展示通知栏【华为mate10 9.0版本测试】;
自定义通知栏
有时间我们不想展示系统给的固定的展示效果,想自己写一个效果,只需要在代码中添加RemoteViews。
//通过xml创建RemoteViews,并且动态改变布局中的内容
RemoteViews remoteView = new Remo