今天看着《第一行代码》,准备实现一下书中所说的notification通知功能。非常简单的代码如下所示
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.send_notice:
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.build();
manager.notify(1,notification);
break;
default:
break;
}
}
结果运行起来,无论怎么样点击button,都不会产生通知。一开始怀疑是模拟器的问题,于是我在手机上尝试,结果仍然显示不出来。这时我心想不应该啊,书上写的怎么会错呢?于是我决定看一下NotificationManager源码看看到底是哪里出了问题。
点开notify方法,发现它其实调用的是notifyAsUser方法,不过看了notifyAsUser方法我还是看不出来为什么显示不出来。忽然看到下面的fixNotification方法中提到了Build.VERSION_CODES,于是我就想到有没有可能是安卓版本的问题?点击Build进去,搜索NotificationManager之后,我终于找到了原因。在安卓版本8.0(O)前面的注释中写到:
* <li>The {@link android.app.NotificationManager} now requires the use of notification channels.</li>
原来在8.0版本之后需要使用notification channels,于是我修改代码
Notification notification = null;
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
String id = "channelId";
String name = "channelName";
NotificationChannel channel = new NotificationChannel(id,name,NotificationManager.IMPORTANCE_LOW);
manager.createNotificationChannel(channel);
notification = new Notification.Builder(this)
.setChannelId(id)
.setContentTitle("This is content title O")
.setContentText("This is content text O")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.build();
}else{
notification = new NotificationCompat.Builder(this)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.build();
}
manager.notify(1,notification);
运行完,就可以成功显示了,记录一下这个小坑, 希望可以帮助到大家