Android框架之路——Notification的使用

简介

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的步骤:

  1. 获取NotificationManager实例;
  2. 实例化Notification.Builder并设置相关属性(Android3.0以上);
  3. 通过 builder.build() 方法生成 Notification 对象;
  4. 通过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(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值