简介
- 用于推送消息,显示在通知中心的通知。
简单示例
1. 创建PendingIntent
创建点击消息时会调用的PendingIntent
。
Intent i = /* new Activity的Intent */;
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
2. 创建Notification
Notification notification = new NotificationCompat.Builder(this)
.setTicker(/* 字符串,消息出现时显示在状态栏的字 */)
.setSmallIcon(/* Drawable,通知的图标 */)
.setContentTitle(/* 字符串,内容标题 */)
.setContentText(/* 字符串,内容文本 */)
.setContentIntent(/* 点击会调用的PendingIntent类型对象 */)
.setAutoCancel(/* 点击后,通知是否从通知中心移除 */)
.build();
3. 发送通知
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
notificationManager.notify(...)
的第一个参数是ID,应该为整个应用唯一,若同一ID发送两次,第二条消息会替换第一条。 PS :实际开发中可以利用这个作为进度条或其他动态特效的实现方式。