近两天啊接受一个新项目,其中有一块是需要开启一个服务,开启服务的时候通知提示状态栏。
废话不多聊,上代码自行理解吧
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this)
.setOngoing(true)//正在运行
.setWhen(System.currentTimeMillis())//什么时候弹出通知栏
.setContentTitle("标题")
.setContentText("内容")
.setAutoCancel(false)//是否自动消失
.setSmallIcon(R.mipmap.ic_launcher);//设置小图标
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.w("Tag","弹框");
//8.0以上弹出通知状态栏
String channelID = "0";
String channelName = "channel_name";
NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelID);
//NOTICE_ID 自己设置的一个int 值,不可为零
startForeground(NOTICE_ID,builder.build());
}
}else {
startForeground(NOTICE_ID,new Notification());
// //弹出通知栏 8.0以下系统弹出方式
// if (notificationManager != null) {
// notificationManager.notify(0, builder.build());
// }
}
亲测有效,如有高手请赐教。