Android-8.0新特性-通知通道配置

  1. 1. Application#onCreate()中配置
  2. 2. 发送通知

Android 8.0开始发送通知需要配置渠道id;

Application#onCreate()中配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//8.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = "你的渠道id";
// 用户可以看到的通知渠道的名字.
CharSequence name = getString(R.string.app_name);
// 用户可以看到的通知渠道的描述
String description = getString(R.string.app_push_message_hint);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.setSound(Uri.parse("android.resource://" + BaseUtil.getPackageInfo(BaseUtil.getApp()).packageName + "/" + R.raw.hint_zz_four), null);
// 设置通知出现时的震动(如果 android 设备支持的话)
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//最后在notificationmanager中创建该通知渠道
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
}
}

发送通知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//发送通知则需要使用渠道id
Intent it = new Intent(context, MemoListActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, it, PendingIntent.FLAG_CANCEL_CURRENT);
Resources res = context.getResources();
Bitmap bmp = BitmapFactory.decodeResource(res, R.mipmap.ic_launcher);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//定义notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "你的渠道id");
builder.setContentTitle("备忘录通知")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(bmp)
.setContentText(content + "")
.setTicker("备忘录通知")
.setSound(Uri.parse("android.resource://您的包名/" + R.raw.hint))
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
// 单机 面板自动取消通知
.setAutoCancel(true)
.setContentIntent(pi);

if (notificationManager != null) {
notificationManager.notify(1, builder.build());// 通过管理器发送通知(通知的id,Notification对象)
}