之前的文章曾经介绍过Android 8.0通知适配的一些方法(详见:
Android通知栏微技巧,8.0系统中通知栏的适配),本文即是在该基础上解决一个开发过程中遇到的问题,不清楚的可以先行查看之前的博客内容,了解Android 8.0之后,通知栏相关的适配内容。
问题描述:
本文所涉及的内容是,在开发过程中,我们会遇到实时更新状态栏通知信息,比如下载的时候,下载进度信息我们需要在通知栏上进行实时的更新,结合通知相关的API我们可以通过下面的代码来实现:
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new NotificationCompat.Builder(AboutusActivity.this, ConstantUtil.NOTIFICATION_CHANNELID)
.setContentTitle("正在下载")
.setContentText("已完成" + progress + "%")
.setWhen(System.currentTimeMillis())
.setSmallIcon(android.R.drawable.stat_sys_download)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.img_download_logo))
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_LIGHTS)
.build();
notificationManager.notify(notificationId, notification);
通知栏适配代码如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = ConstantUtil.NOTIFICATION_CHANNELID;
String channelName = ConstantUtil.NOTIFICATION_CHANNELNAME;
int importance = NotificationManager.IMPORTANCE_DEFAULT;
createNotificationChannel(channelId, channelName, importance);
}
@TargetApi(Build.VERSION_CODES.O)
private void createNotificationChannel(String channelId, String channelName, int importance) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
通过 notificationManager.notify(notificationId, notification); 进行通知的更新,相同的notificationId会覆盖,但是在Android 8.0上会出现更新的过程中一直弹出提示音的问题,针对这个问题解决方案如下:
解决方法:
1.创建NotificationChannel时,将importance参数设置为NotificationManager.IMPORTANCE_LOW
2.更新channelId,设置为一个新的值,然后设置channel.setSound(null, null)
3.notificationBuidler.setOnlyAlertOnce(true)设置为true,这样每次只会提醒一次声音
创建NotificationChannel方法
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(ConstantUtil.NOTIFICATION_CHANNELID, ConstantUtil.NOTIFICATION_CHANNELNAME, NotificationManager.IMPORTANCE_LOW);
channel.enableVibration(false);
channel.enableLights(true);
channel.setSound(null, null);
if (notificationManager != null)
notificationManager.createNotificationChannel(channel);
}
设置Notification方法:
notification = new NotificationCompat.Builder(AboutusActivity.this, ConstantUtil.NOTIFICATION_CHANNELID)
.setContentTitle("正在下载")
.setContentText("已完成" + progress + "%")
.setWhen(System.currentTimeMillis())
.setSmallIcon(android.R.drawable.stat_sys_download)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.img_download_logo))
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_LIGHTS)
.setOnlyAlertOnce(true)
.build();
notificationManager.notify(notificationId, notification);
通过如上设置,即可解决上述问题的出现,如有更好的解决方案欢迎留言讨论