1.简介
通知推送的使用方式和AlertDialog的使用方式差不多,都是先用build构造并设置参数,最后由通知服务推送。
2.使用
当目标sdk版本大于等于26时,按照原来的方法直接弹出消息会报错 ****NotificationService: No Channel found for ****。下面是解决方法。
- 首先要建立通道(也就是设置中的通知类别,如图中的“消息”),示例代码如下。
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);
- 发送消息,注意要在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);
}