Android的通知系统提供了丰富的自定义功能,其中包括自定义通知布局、通知声音、震动、灯光等。以下是一些代码示例:
您可以使用RemoteViews类定义自定义通知布局。例如:
// 从布局文件中创建RemoteViews对象 RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
// 设置通知内容 contentView.setTextViewText(R.id.notification_title, "Custom Notification Title"); contentView.setTextViewText(R.id.notification_text, "Custom Notification Text");
// 创建通知实例 NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_icon) .setContentIntent(pendingIntent) .setContent(contentView);
// 发送通知 NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(notificationId, builder.build());
您可以使用NotificationCompat类设置通知的声音、震动和灯光等。例如:
// 创建通知声音 Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// 创建通知实例 NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_icon) .setContentIntent(pendingIntent) .setContentTitle("Notification Title") .setContentText("Notification Text") .setSound(soundUri) .setVibrate(new long[]{100, 200, 300, 400, 500});
// 发送通知 NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(notificationId, builder.build());
您可以使用NotificationCompat类修改通知的默认行为。例如:
// 创建通知实例 NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_icon) .setContentIntent(pendingIntent) .setContentTitle("Notification Title") .setContentText("Notification Text") .setAutoCancel(true); // 点击通知后自动取消
// 发送