下面来看一下创建并显示一个 Notification 的步骤。创建和显 示一个 Notification 需要如下 5 步:
1. 通过 getSystemService 方法获得一个 NotificationManager 对象。
2. 创建一个 Notification 对象。每一个 Notification 对应一个 Notification 对象。在这一步需要设置显示在屏幕上方状态栏的通知消息、通知消息前方的图像资源 ID 和发出通知的时间。一般为当前时间。
3. 由于 Notification 可以与应用程序脱离。也就是说,即使应用程序被关闭, Notification 仍然会显示在状态栏 中。当应用程序再次启动后,又可以重新控制这些 Notification 。如清除或替换它们。因此,需要创建一个 PendingIntent 对象。该对象由 Android 系统负责维护,因此,在应用程序关闭后,该对象仍然不会被释放。
4. 使用 Notification 类的 setLatestEventInfo 方法设置 Notification 的详细信息。
5. 使用 NotificationManager 类的 notify 方法显示 Notification 消息。在这一步需要指定标识 Notification 的唯一 ID 。这个 ID 必须相对于同一个 NotificationManager 对象是唯一的,否则就会覆盖相同 ID 的 Notificaiton 。