Notification 实例怎么使用
时间: 2023-08-31 11:06:42 浏览: 61
要使用 Notification 实例,您需要先创建一个 Notification 对象,然后使用 NotificationManager 将其发送到设备的通知中心。以下是一个简单的示例:
```
// 创建 Notification 实例
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// 发送 Notification
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(notificationId, builder.build());
```
在上面的示例中,我们使用 NotificationCompat.Builder 创建了一个简单的 Notification 实例,并设置了一些基本的属性(如图标、标题和文本)。然后,我们使用 NotificationManagerCompat 发送该通知,其中 notificationId 是一个唯一的整数,用于标识该通知。
当用户点击通知时,您可以在 PendingIntent 中指定一个操作,例如打开某个 Activity 或启动某个服务。以下是一个使用 PendingIntent 的示例:
```
// 创建 PendingIntent
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// 添加 PendingIntent 到 Notification 实例
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent);
```
在上面的示例中,我们创建了一个 PendingIntent,该 PendingIntent 将打开 MainActivity。然后,我们将 PendingIntent 添加到 Notification 实例中,使用户可以在点击通知时打开 MainActivity。