0.前言
Android8.0后,Notification通知信息的制作有了改变,引入了信道的概念。网上很多关于Notification通知信息的文章要嘛过时了,要嘛版本判断条件语句很复杂。本文章的方法可以通用新旧版本。加入的条件语句仅2行。
1.Notification服务的获取
测试了很多办法,下面的办法可以通用新旧版本
//需要Context对象或在Activity及Service或Fragment下运行
NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
2.Notification服务配置信道。
Android 8.0以上需要配置信道,之前的不需要,这步骤可以忽略
private static final String CHANNEL_ID = "1";
private static final int NOTIFICATION_ID= 2;
private static final String CHANNEL_NAME = "channel_start_service";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { //Android 8.0以上需要配置信道
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
3.notification的制作
测试了很多办法,下面的办法可以通用新旧版本,其中CHANNEL_ID低版本可以不写。高版本必须制定信道ID。但是写了比较通用
Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
.setTicker(resources.getString(R.string.notification_title))
.setSmallIcon(android.R.drawable.ic_menu_report_image)
.setContentTitle(resources.getString(R.string.notification_title))
.setContentText(resources.getString(R.string.notification_text))
.setAutoCancel(true)
.setContentIntent(pi)
.build();
4.发布notification
NOTIFICATION_ID一样的话,会替换掉之前的notifycation。如果不一样,就会显示出2条notifycation
notificationManager.notify(NOTIFICATION_ID,notification);