Android通知推送(解决NotificationService: No Channel found for***问题)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43219615/article/details/99764715

1.简介

通知推送的使用方式和AlertDialog的使用方式差不多,都是先用build构造并设置参数,最后由通知服务推送。
通知图片

2.使用

当目标sdk版本大于等于26时,按照原来的方法直接弹出消息会报错 ****NotificationService: No Channel found for ****。下面是解决方法。

  1. 首先要建立通道(也就是设置中的通知类别,如图中的“消息”),示例代码如下。
    通知类别
private void createNotificationChannel(String channelId, String channelName, int importance) {
	NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
	NotificationManager notificationManager  = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
	notificationManager.createNotificationChannel(notificationChannel);
}
//创建一个message通道,名字为消息
createNotificationChannel("message", "消息", NotificationManager.IMPORTANCE_HIGH);
  1. 发送消息,注意要在build里加上通道id,不然会报错。示例代码如下。
private void sendNotification(String title, String content) {
	Intent intent = new Intent(this, MainActivity.class);
	PendingIntent pendingIntent = PendingIntent.getActivity(this, R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "message");   
  	builder.setContentIntent(pendingIntent).setAutoCancel(true).setSmallIcon(R.drawable.ic_demo).setTicker("提示消息").setWhen(System.currentTimeMillis())
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_demo)).setContentTitle(title).setContentText(content);
	Notification notification = builder.build();
	NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);
}

猜你喜欢

转载自blog.csdn.net/weixin_43219615/article/details/99764715