要实现Android 8/9的通知调度,可以使用以下步骤和示例代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "channel_id";
CharSequence channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Notification Title")
.setContentText("Notification Content");
int notificationId = 1;
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
notificationManager.cancel(notificationId);
这是一个基本的示例,你可以根据需要自定义通知的样式、行为和事件处理。请记住,在Android 8及以上版本,通知必须与NotificationChannel关联,否则通知将无法显示。