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

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);
}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值