引言:
几个月前,我尝试着按照网上的例子写了一段发送通知的代码,结果运行在我的手机并没有起任何的作用(版本为Andriod9.0),结果用一部6.0的手机果然就发送出去了通知。于是我明白了,是版本的问题,最后我发现要能够在 Android 8.0 及更高版本上提供通知,首先必须向createNotificationChannel() 传递 NotificationChannel 的实例,以便在系统中注册应用的通知渠道。
实现:
1.创建渠道:在发送通知前,先调用此函数,多次调用此函数也是安全的。常量CHANNEL_ID,CHANNEL_NAME,CHANNEL_DESCRIPTION,CHANNEL_ID均为自定义常量,按照类型定义就完事了。注意创建的渠道的id与创建的通知的渠道id是相对应的,不同渠道可以创建不同类型的通知。
private void createChannel() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription(CHANNEL_DESCRIPTION);
NotificationManager notificationManager=getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
}
2.发送通知:调用此函数便可发送一条通知,我这是带点击跳转的一条通知。不需跳转,则不需创建pendingIntent。
private void sendNotification() {
/**
*先创建渠道,才能发送通知
*/
createChannel();
Intent intent=new Intent(this,NotifyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,0);
NotificationCompat.Builder builder=new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Hello User")
.setContentText("This is a message")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManagerCompat=NotificationManagerCompat.from(this);
notificationManagerCompat.notify(NOTIFY_ID,builder.build());
}
效果图如下: