注册通知分类
- Android 8.0之后的版本,要求通知必须指定notification channel,因此在app启动之后,要注册Channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(id, name, importance);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
创建通知
- 不同的Android版本创建通知的形式不同,因此通过NotificationCompat创建通知
NotificaitonCompat.Builder notificationBuilder = new NotificationCompat.Builer(context, channel_id)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title)
.setContentText(content)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
定义通知点击逻辑
Intent intent = new Intent(context, Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, request_code, intent, flag);
notificationBuilder.setContentIntent(pendingIntent);
显示通知
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(notification_id, notificationBuilder.build());