在尝试了网上各种向通知栏发送通知的教程后,发现能用的教程的很少,但是皇天不负有心人,最后还是找到一篇很实用的教程,
链接在此:https://blog.youkuaiyun.com/android157/article/details/82852001
接下来记录下我的简单的demo,实现点击按钮向通知栏发送通知,但是关于点击通知的处理,暂时被我省略了,
因为的目的是成功发送通知:
所以代码只贴了点击事件处理的代码,也是发送通知的关键性代码
String id = "channel_001";
String name = "name";
NotificationManager notificationManager = (NotificationManager)
this.getSystemService(NOTIFICATION_SERVICE);
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//判断API
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(mChannel);
notification = new Notification.Builder(this)
.setChannelId(id)
.setContentTitle("活动")
.setContentText("您有一项新活动")
.setSmallIcon(R.mipmap.ic_launcher_round).build();
}else{
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("活动")
.setContentText("您有一项新活动")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setOngoing(true)
.setChannelId(id);//无效
notification = notificationBuilder.build();
}
notificationManager.notify(1,notification);
运行结果: