android8.0带来的新的特性—— notification channel
SDK上是这样描述channel的
A representation of settings that apply to a collection of similarly themed notifications.
简单的说,channel用来代表一系列相似的通知,即拥有相同特性的通知,使用channel可以避免创建通知产生的冗余代码
1.创建Notification Channel
单个channel
NotificationChannel channel = new NotificationChannel("id", "name", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
多个channel的创建
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannels(Arrays.asList(
new NotificationChannel(
"id",
"name",
NotificationManager.IMPORTANCE_LOW),
new NotificationChannel(
"id1",
"name1",
NotificationManager.IMPORTANCE_DEFAULT),
new NotificationChannel(
"id2",
"name2",
NotificationManager.IMPORTANCE_HIGH)
));
channel也支持其他属性的设置,例如震动模式,声音,led灯光等
2.创建通知
Notification.Builder builder = new Notification.Builder(this, "id1");
Notification notification = builder.setContentTitle("title").build();
notificationManager.notify(1, notification);
或者
Notification.Builder builder = new Notification.Builder(this);
Notification notification = builder.setChannelId("id1").setContentTitle("title").build();
notificationManager.notify(1, notification);
需要注意的是,在Android8.0(app的targetSdkVersion >= 26)上创建通知的时候必须指定channel,否则无法正常显示,见notificationmanagerservice
void enqueueNotificationInternal(final String pkg, final String opPkg, final int callingUid,
final int callingPid, final String tag, final int id, final Notification notification,
int incomingUserId) {
checkCallerIsSystemOrSameApp(pkg);
....
final NotificationChannel channel = mRankingHelper.getNotificationChannel(pkg,
notificationUid, channelId, false /* includeDeleted */);
if (channel == null) {
doChannelWarningToast("Developer warning for package \"" + pkg + "\"\n" +
"Failed to post notification on channel \"" + channelId + "\"\n" +
"See log for more details");
return;
}
...
mHandler.post(new EnqueueNotificationRunnable(userId, r));
}
3.兼容方案
一般使用NotificationCompat类而不是Notification创建通知,并且要加入系统版本的判断
NotificationCompat.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
builder = new NotificationCompat.Builder(this, CHANNEL_ID);
} else
{
builder = new NotificationCompat.Builder(this);
}
...
参考:https://developer.android.google.cn/reference/android/app/NotificationChannel