Android8.0中新增了一个NotificationChannel,如果不为Notification指定NotificationChannel就会Toast一个错误
网上虽然有许多讲解怎样填这个坑的教程,但是好像没有对构造方法里各个参数含义的一个解释,因此我找到了对应的开发文档并对其进行整理
文档地址:
https://developer.android.com/reference/android/app/NotificationChannel
NotificationChannel初始化的时候需要填写三个参数,id,name,importance。
id:String类型,NotificationChannel的id ,每个包必须是唯一的。如果值太长,可能会被截断
name:CharSequence类型,NotificationChannel的用户可见名称,当系统区域(System locale)设置更改时,可以通过侦听Intent.ACTION_LOCALE_CHANGED广播,最大建议长度为40个字符,如果太长可能会被截断
importance:int类型,NotificationChannel的重要性,它控制发送到这个通道的通知中断的方式,具体取值如下表所示
来个例子:
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//在这里判断系统版本是否大于8.0,大于8.0则创建一个Channel
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//这里指定channel id 为0
NotificationChannel channel = new NotificationChannel("0","channelTest",NotificationManager.IMPORTANCE_HIGH);
}
Notification notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("通知标题")
.setContentText("通知文本")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_background))
//这里将刚才的channel id传入
.setChannelId("0")
.build();
manager.notify(1,notification);
}
这样在8.0系统下,也可以正常显示通知了