android学习笔记-------notification类显示通知

notification类可以对程序设置推送信息,就是对状态栏的信息进行推送。

  1. 首先需要一个NotificationManager来对通知进行管理,调用Context的getSystemService()方法获取到。
    在这里插入图片描述
  2. 创建一个Notification.Builder对象:
    Notification.Builder builder=new Notification.Builder(this);
    通过这个对象的方法来设置各种属性在这里插入图片描述
  3. 使用Notification.Builder的build()方法来创建Notification对象。
  4. 最后,使用NotificationManager.notify()方法,发送通知。notify()方法接收两个参数,第一个参数是id,要保证为每个通知所指定的id都是不同的。第二个参数则是Notification对象。
    若要实现点击通知跳跃,需要使用PendingIntent
    PendingIntent 是一种特殊的 Intent ,字面意思可以解释为延迟的 Intent ,用于在某个事件结束后执行特定的 Action 。从上面带 Action 的通知也能验证这一点,当用户点击通知时,才会执行。
    PendingIntent 是 Android 系统管理并持有的用于描述和获取原始数据的对象的标志(引用)。也就是说,即便创建该PendingIntent对象的进程被杀死了,这个PendingItent对象在其他进程中还是可用的。
    日常使用中的短信、闹钟等都用到了 PendingIntent。
    PendingIntent 具有以下几种 flag:
FLAG_CANCEL_CURRENT:如果当前系统中已经存在一个相同的 PendingIntent 对象,那么就将先将已有的 PendingIntent 取消,然后重新生成一个 PendingIntent 对象。
 
FLAG_NO_CREATE:如果当前系统中不存在相同的 PendingIntent 对象,系统将不会创建该 PendingIntent 对象而是直接返回 null 。
 
FLAG_ONE_SHOT:该 PendingIntent 只作用一次。
 
FLAG_UPDATE_CURRENT:如果系统中已存在该 PendingIntent 对象,那么系统将保留该 PendingIntent 对象,但是会使用新的 Intent 来更新之前 PendingIntent 中的 Intent 对象数据,例如更新 Intent 中的 Extras 。

说一下怎么实现吧:

  1. 首先,要创建一个Intent,要跳转到哪就写哪。
  2. 然后,创建PendingIntent,调用PendingIntent.getActivity()方法,启动一个Activity。这个方法中包括4个参数,第一个是上下文对象,第二个requestCode(请求代码),第三个就是Intent对象了,第四个就是FLAG。
  3. 最后调用Notification.Builder的setContentIntent()方法设置完成。
    在这里插入图片描述
发布了18 篇原创文章 · 获赞 8 · 访问量 377

猜你喜欢

转载自blog.csdn.net/qq_34423913/article/details/103728203