📅  最后修改于: 2023-12-03 14:39:09.733000             🧑  作者: Mango
在 Android 应用中,通知是非常常见的一种 UI 元素。它可以在后台执行任务时向用户发送重要信息,提高用户体验。
创建通知需要以下步骤:
下面是一个创建通知的示例代码:
// 创建通知渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
// 创建通知构建器
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// 显示通知
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
可扩展通知可以在通知栏中显示更多的信息,以便用户能够更好地了解通知的内容。示例代码如下:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
可交互通知允许用户通过通知栏直接执行某些操作,例如回复消息、打开应用等。示例代码如下:
// 创建 PendingIntent
Intent intent = new Intent(this, MyBroadcastReceiver.class);
intent.setAction("ACTION_REPLY");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// 创建回复操作
RemoteInput remoteInput = new RemoteInput.Builder(KEY_REPLY)
.setLabel("Reply")
.build();
NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
R.drawable.ic_reply, "Reply", pendingIntent)
.addRemoteInput(remoteInput)
.build();
// 创建通知构建器
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.addAction(replyAction)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
通知是 Android 应用中重要的 UI 元素之一,它可以向用户发送重要信息并提高用户体验。在创建通知时,需要注意创建通知渠道、设置通知构建器、显示通知等步骤。同时,对于可扩展通知和可交互通知,也需要了解相应的实现方式。