Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
1 Introduction
Notify the push of use and the use of almost AlertDialog are constructed first with the build and set parameters, the final push notification service.
2. Use
When the target sdk version than or equal to 26, the method according to the original message will pop up directly given ****NotificationService: No Channel found for ****. Here is the solution.
- First, to establish channel (i.e. notification category settings, as shown in the "message"), the following sample code.
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);
- To send a message, pay attention to add a channel id in the build, or will be error. Sample code is as follows.
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);
}