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

1.简介

通知推送的使用方式和AlertDialog的使用方式差不多,都是先用build构造并设置参数,最后由通知服务推送。
Android通知推送(解决NotificationService: No Channel found for***问题)_第1张图片

2.使用

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

  1. 首先要建立通道(也就是设置中的通知类别,如图中的“消息”),示例代码如下。
    Android通知推送(解决NotificationService: No Channel found for***问题)_第2张图片
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);
}

你可能感兴趣的:(《零基础到App上线》学习笔记)