简介
Notification,是一种具有全局效果的通知,可以在系统的通知栏中显示。当 APP 向系统发出通知时,它将先以图标的形式显示在通知栏中。用户可以下拉通知栏查看通知的详细信息。通知栏和抽屉式通知栏均是由系统控制,用户可以随时查看。
PendingIntent
pendingIntent是一种特殊的Intent。pendingIntent:等待、未决定的Intent。
主要的区别在于Intent的执行立刻的,而pendingIntent的执行不是立刻的。pendingIntent执行的操作实质上是参数传进来的Intent的操作,但是使用pendingIntent的目的在于只有满足条件才能执行它所包含的Intent操作。
主要使用范围:Notificatio,短消息发送和警报器执行等等。
获取PendingIntent方式:
//获取一个用于启动 Activity 的 PendingIntent 对象
public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags);
//获取一个用于启动 Service 的 PendingIntent 对象
public static PendingIntent getService(Context context, int requestCode, Intent intent, int flags);
//获取一个用于向 BroadcastReceiver 广播的 PendingIntent 对象
public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)
PendingIntent具有以下几种flag:
- **FLAG_CANCEL_CURRENT:**如果当前系统中已经存在一个相同的 PendingIntent 对象,那么就将先将已有的 PendingIntent 取消,然后重新生成一个 PendingIntent 对象。
- **FLAG_IMMUTABLE:**创建的PendingIntent不可变,API23加入。
- **FLAG_NO_CREATE:**如果当前系统中不存在相同的 PendingIntent 对象,系统将不会创建该 PendingIntent 对象而是直接返回 null 。
- **FLAG_ONE_SHOT:**该 PendingIntent 只作用一次。
- **FLAG_UPDATE_CURRENT:**如果系统中已存在该 PendingIntent 对象,那么系统将保留该 PendingIntent 对象,但是会使用新的 Intent 来更新之前 PendingIntent 中的 Intent 对象数据,例如更新 Intent 中的 Extras。
普通Notification
发送Notification的步骤:
- 获取NotificationManager实例;
- 实例化Notification.Builder并设置相关属性(Android3.0以上);
- 通过 builder.build() 方法生成 Notification 对象;
- 通过NotificationManager实例发送通知。
代码实现:
public void sendNotification(View view) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("普通通知")
.setContentText("这是普通通知内容")
.setAutoCancel(true)
.build();
manager.notify(1, notification);
}
利用PendingIntent给Notification设置 Action:
public void common_notification(View view) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
PendingIntent intent = PendingIntent.getActivity(