全面解析Notification

移动开发 Android
Notification在Android中使用的频率可以说是非常高的,本文我将围绕着Notification的各方面进行解析,使大家对Notification有更好的认识。

Notification在Android中使用的频率可以说是非常高的,本文我将围绕着Notification的各方面进行解析,使大家对Notification有更好的认识。

Notification的使用步骤

1.获取NotificationManager

  1. NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

2.创建NotificationCompat.Builder

  1. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); 

3.对Builder设置一些Notification相关属性:

  1. mBuilder.setContentTitle("标题")//设置通知栏标题   
  2.     .setContentText("内容") //设置通知栏显示内容  
  3.     .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //设置通知栏点击意图   
  4. //  .setNumber(number) //设置通知集合的数量   
  5.     .setTicker("通知到来") //通知***出现在通知栏,带上升动画效果的   
  6.     .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间   
  7.     .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级   
  8. //  .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消     
  9.     .setOngoing(false)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)   
  10.     .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合   
  11.     //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission   
  12.     .setSmallIcon(R.drawable.ic_launcher);//设置通知小ICON   

4.使用Builder创建通知

  1. Notification notification = mBuilder.build(); 

5.使用NotificationManager将通知推送出去

  1. int id = 199; 
  2. LogUtils.d(TAG, "创建通知"); 
  3. mNotificationManager.notify(id, notification);  

Notification重要方法解析

Notification 的基本操作主要有创建、更新、取消这三种。一个 Notification 的必要属性有三项,如果不设置则在运行时会抛出异常:

  1. 小图标,通过 setSmallIcon() 方法设置
  2. 标题,通过 setContentTitle() 方法设置
  3. 内容,通过 setContentText() 方法设置

除了以上三项,其它均为可选项。虽然如此,但还是应该给 Notification 设置一个 Action ,这样就可以直接跳转到 App 的某个 Activity 、启动一个 Service 或者发送一个 Broadcast。否则,Notification 仅仅只能起到通知的效果,而不能与用户交互。

当系统接收到通知时,可以通过震动、响铃、呼吸灯等多种方式进行提醒。

1) setSmallIcon() 与 setLargeIcon()

在 NotificationCompat.Builder 中有设置通知的大小图标的两个方法。这两个方法有什么区别呢?当 setSmallIcon() 与 setLargeIcon() 同时存在时, smallIcon 显示在largeIcon的右下角;当只设置 setSmallIcon() 时, smallIcon 显示在左侧。看下图你就明白了。对于部分 ROM ,可能修改过源码,如 MIUI 上通知的大图标和小图标是没有区别的。 

 

 

 

Google 官方是这么解释 setSmallIcon() 这个方法的:

  1. Set the small icon resource, which will be used to represent the notification in the status bar. The platform template for the expanded view will draw this icon in the left, unless a large icon has also been specified, in which case the small icon will be moved to the right-hand side. 

2) 设置提醒标志符Flags

方法解释:提醒标志符,向通知添加声音、闪灯和振动效果等设置达到通知提醒效果,可以组合多个属性

a) 创建通知栏之后通过给他添加.flags属性赋值。

  1. Notification notification = mBuilder.build();   
  2. notification.flags = Notification.FLAG_AUTO_CANCEL;   

b) 通过setContentIntent(PendingIntent intent)方法中的意图设置对应的flags

  1. public PendingIntent getDefalutIntent(int flags){ 
  2.  
  3. PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, new Intent(), flags); 
  4.  
  5. return pendingIntent; 
  6.  
  7.  

各标志符介绍

  1. Notification.FLAG_SHOW_LIGHTS              //三色灯提醒,在使用三色灯提醒时候必须加该标志符 
  2. Notification.FLAG_ONGOING_EVENT          //发起正在运行事件(活动中) 
  3. Notification.FLAG_INSISTENT   //让声音、振动***循环,直到用户响应 (取消或者打开) 
  4. Notification.FLAG_ONLY_ALERT_ONCE  //发起Notification后,铃声和震动均只执行一次 
  5. Notification.FLAG_AUTO_CANCEL      //用户单击通知后自动消失 
  6. Notification.FLAG_NO_CLEAR          //只有全部清除时,Notification才会清除 ,不清楚该通知(QQ的通知无法清除,就是用的这个) 
  7. Notification.FLAG_FOREGROUND_SERVICE    //表示正在运行的服务  

3) .setDefaults(int defaults) (NotificationCompat.Builder中的方法,用于设置通知到来时,通过什么方式进行提示)

方法解释:向通知添加声音、闪灯和振动效果的最简单、使用默认(defaults)属性,可以组合多个属性(和方法1中提示效果一样的)

对应属性:

Notification.DEFAULT_VIBRATE //添加默认震动提醒 需要 VIBRATE permission

Notification.DEFAULT_SOUND // 添加默认声音提醒

Notification.DEFAULT_LIGHTS// 添加默认三色灯提醒

Notification.DEFAULT_ALL// 添加默认以上3种全部提醒

  1. /** 
  2. * 显示带有默认铃声、震动、呼吸灯效果的通知 
  3. * 如需实现自定义效果,请参考后面三个例子 
  4. */ 
  5. private void showNotifyWithMixed() { 
  6.    NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  7.            .setSmallIcon(R.mipmap.ic_launcher) 
  8.            .setContentTitle("我是有铃声+震动+呼吸灯效果的通知"
  9.            .setContentText("库里就是叼~"
  10.            //等价于setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE); 
  11.            .setDefaults(Notification.DEFAULT_ALL); 
  12.    mManager.notify(5, builder.build()); 
  13.  

4) setVibrate(long[] pattern)

方法解释:设置震动的时间

  1. .setVibrate(new long[] {0,300,500,700});   

实现效果:延迟0ms,然后振动300ms,在延迟500ms,接着在振动700ms。

还有另外一种写法:

  1. mBuilder.build().vibrate = new long[] {0,300,500,700};   

如果希望设置默认振动方式,设置了方法(2)中默认为DEFAULT_VIBRATE 即可。

例子:

  1. /** 
  2. * 展示有震动效果的通知,需要在AndroidManifest.xml中申请震动权限 
  3. * <uses-permission android:name="android.permission.VIBRATE" /> 
  4. * 补充:测试震动的时候,手机的模式一定要调成铃声+震动模式,否则你是感受不到震动的 
  5. */ 
  6. private void showNotifyWithVibrate() { 
  7.    //震动也有两种设置方法,与设置铃声一样,在此不再赘述 
  8.    long[] vibrate = new long[]{0, 500, 1000, 1500}; 
  9.    NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  10.            .setSmallIcon(R.mipmap.ic_launcher) 
  11.            .setContentTitle("我是伴有震动效果的通知"
  12.            .setContentText("颤抖吧,凡人~"
  13.            //使用系统默认的震动参数,会与自定义的冲突 
  14.            //.setDefaults(Notification.DEFAULT_VIBRATE) 
  15.            //自定义震动效果 
  16.            .setVibrate(vibrate); 
  17.    //另一种设置震动的方法 
  18.    //Notification notify = builder.build(); 
  19.    //调用系统默认震动 
  20.    //notify.defaults = Notification.DEFAULT_VIBRATE; 
  21.    //调用自己设置的震动 
  22.    //notify.vibrate = vibrate; 
  23.    //mManager.notify(3,notify); 
  24.    mManager.notify(3, builder.build()); 
  25.  

4)方法:.setLights(intledARGB ,intledOnMS ,intledOffMS )

方法解释:android支持三色灯提醒,这个方法就是设置不同场景下的不同颜色的灯。

描述:其中ledARGB 表示灯光颜色、 ledOnMS 亮持续时间、ledOffMS 暗的时间。

注意:

1)只有在设置了标志符Flags为Notification.FLAG_SHOW_LIGHTS的时候,才支持三色灯提醒。

2)这边的颜色跟设备有关,不是所有的颜色都可以,要看具体设备。

  1. Notification notify = mBuilder.build();   
  2. notify .setLights(0xff00eeff, 500, 200)  

同理,以下方法也可以设置同样效果:

  1. Notification notify = mBuilder.build();   
  2. notify.flags = Notification.FLAG_SHOW_LIGHTS;   
  3. notify.ledARGB = 0xff00eeff;   
  4. notify.ledOnMS = 500;   
  5. notify.ledOffMS = 400;   

如果希望使用默认的三色灯提醒,设置了方法(2)中默认为DEFAULT_LIGHTS即可。

例子:

  1. /** 
  2. * 显示带有呼吸灯效果的通知,但是不知道为什么,自己这里测试没成功 
  3. */ 
  4. private void showNotifyWithLights() { 
  5.    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  6.            .setSmallIcon(R.mipmap.ic_launcher) 
  7.            .setContentTitle("我是带有呼吸灯效果的通知"
  8.            .setContentText("一闪一闪亮晶晶~"
  9.            //ledARGB 表示灯光颜色、 ledOnMS 亮持续时间、ledOffMS 暗的时间 
  10.            .setLights(0xFF0000, 3000, 3000); 
  11.    Notification notify = builder.build(); 
  12.    //只有在设置了标志符Flags为Notification.FLAG_SHOW_LIGHTS的时候,才支持呼吸灯提醒。 
  13.    notify.flags = Notification.FLAG_SHOW_LIGHTS; 
  14.    //设置lights参数的另一种方式 
  15.    //notify.ledARGB = 0xFF0000; 
  16.    //notify.ledOnMS = 500; 
  17.    //notify.ledOffMS = 5000; 
  18.    //使用handler延迟发送通知,因为连接usb时,呼吸灯一直会亮着 
  19.    Handler handler = new Handler(); 
  20.    handler.postDelayed(new Runnable() { 
  21.        @Override 
  22.        public void run() { 
  23.            mManager.notify(4, builder.build()); 
  24.        } 
  25.    }, 10000); 
  26.  

5)方法:.setSound(Uri sound)

方法解释:设置默认或则自定义的铃声,来提醒。

  1. //获取默认铃声   
  2. .setDefaults(Notification.DEFAULT_SOUND)   
  3. //获取自定义铃声   
  4. .setSound(Uri.parse("file:///sdcard/dance.mp3"))   
  5. //获取Android多媒体库内的铃声   
  6. .setSound(Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "5"))    

同理相同效果的另一种设置方法这边就不讲, 和上面的都是一样的。

例子:

  1. /** 
  2. * 展示有自定义铃声效果的通知 
  3. * 补充:使用系统自带的铃声效果:Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6"); 
  4. */ 
  5. private void showNotifyWithRing() { 
  6.    NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  7.            .setSmallIcon(R.mipmap.ic_launcher) 
  8.            .setContentTitle("我是伴有铃声效果的通知"
  9.            .setContentText("美妙么?安静听~"
  10.            //调用系统默认响铃,设置此属性后setSound()会无效 
  11.            //.setDefaults(Notification.DEFAULT_SOUND) 
  12.            //调用系统多媒体裤内的铃声 
  13.            //.setSound(Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"2")); 
  14.            //调用自己提供的铃声,位于 /res/values/raw 目录下 
  15.            .setSound(Uri.parse("android.resource://com.littlejie.notification/" + R.raw.sound)); 
  16.    //另一种设置铃声的方法 
  17.    //Notification notify = builder.build(); 
  18.    //调用系统默认铃声 
  19.    //notify.defaults = Notification.DEFAULT_SOUND; 
  20.    //调用自己提供的铃声 
  21.    //notify.sound = Uri.parse("android.resource://com.littlejie.notification/"+R.raw.sound); 
  22.    //调用系统自带的铃声 
  23.    //notify.sound = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"2"); 
  24.    //mManager.notify(2,notify); 
  25.    mManager.notify(2, builder.build()); 
  26.  

6)方法:.setPriority(int pri)

方法解释:设置优先级(实际项目中并无大用,设置***级也不会使得你的通知栏出现在***位) 

 

 

 

对应属性:

  1. Notification.PRIORITY_DEFAULT(优先级为0)
  2. Notification.PRIORITY_HIGH
  3. Notification.PRIORITY_LOW
  4. Notification.PRIORITY_MAX(优先级为2)
  5. Notification.PRIORITY_MIN(优先级为-2)

Notification.PRIORITY_MAX是优先级***,Notification.PRIORITY_MIN优先级***

7)方法:setOngoing(boolean ongoing)

方法解释:设置为ture,表示它为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)

PS:我们看到360手机卫士的通知栏一直固定在手机中,就是通过设置这个标记,使用该标记后你的通知栏无法被用户手动进行删除,只能通过代码进行删除,慎用

8)setProgress(int max, int progress,boolean indeterminate)

属性:max:进度条***数值 、progress:当前进度、indeterminate:表示进度是否不确定,true为不确定,false为确定

功能:设置带进度条的通知,可以在下载中使用

注意:此方法在4.0及以后版本才有用,如果为早期版本:需要自定义通知布局,其中包含ProgressBar视图

使用:如果为确定的进度条:调用setProgress(max, progress, false)来设置通知,在更新进度的时候在此发起通知更新progress,并且在下载完成后要移除进度条,通过调用setProgress(0, 0, false)既可。

如果为不确定(持续活动)的进度条,这是在处理进度无法准确获知时显示活动正在持续,所以调用setProgress(0, 0, true) ,操作结束时,调用setProgress(0, 0, false)并更新通知以移除指示条

9)如何更新 Notification

更新通知很简单,只需要再次发送相同 ID 的通知即可,如果之前的通知还未被取消,则会直接更新该通知相关的属性;如果之前的通知已经被取消,则会重新创建一个新通知。

更新通知跟发送通知使用相同的方式。

  1. private void refreshNotification() { 
  2.    //获取NotificationManager实例 
  3.    NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
  4.    //实例化NotificationCompat.Builde并设置相关属性 
  5.    NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  6.            //设置小图标 
  7.            .setSmallIcon(R.mipmap.icon_fab_repair) 
  8.            //设置通知标题 
  9.            .setContentTitle("最简单的Notification"
  10.            //设置通知内容 
  11.            .setContentText("只有小图标、标题、内容"
  12.            //设置通知时间,默认为系统发出通知的时间,通常不用设置 
  13.            //.setWhen(System.currentTimeMillis()); 
  14.    //通过builder.build()方法生成Notification对象,并发送通知,id=1 
  15.    notifyManager.notify(1, builder.build()); 
  16.  

10)如何取消 Notification?

取消通知有如下 5 种方式:

1. 点击通知栏的清除按钮,会清除所有可清除的通知

2. 设置了 setAutoCancel() 或 FLAG_AUTO_CANCEL 的通知,点击该通知时会清除它

3. 通过 NotificationManager 调用 cancel(int id) 方法清除指定 ID 的通知

4. 通过 NotificationManager 调用 cancel(String tag, int id) 方法清除指定 TAG 和 ID 的通知

5. 通过 NotificationManager 调用 cancelAll() 方法清除所有该应用之前发送的通知

如果你是通过 NotificationManager.notify(String tag, int id, Notification notify) 方法创建的通知,那么只能通过 NotificationManager.cancel(String tag, int id) 方法才能清除对应的通知,调用NotificationManager.cancel(int id) 无效。

例子: 

  1. public class DemoActivity extends Activity implements View.OnClickListener { 
  2.  
  3.     //Notification.FLAG_FOREGROUND_SERVICE    //表示正在运行的服务 
  4.     public static final String NOTIFICATION_TAG = "test"
  5.     public static final int DEFAULT_NOTIFICATION_ID = 1; 
  6.  
  7.     private NotificationManager mNotificationManager; 
  8.  
  9.     @Override 
  10.     protected void onCreate(Bundle savedInstanceState) { 
  11.         super.onCreate(savedInstanceState); 
  12.         setContentView(R.layout.activity_simple_notification); 
  13.  
  14.         findViewById(R.id.btn_remove_all_notification).setOnClickListener(this); 
  15.         findViewById(R.id.btn_send_notification).setOnClickListener(this); 
  16.         findViewById(R.id.btn_remove_notification).setOnClickListener(this); 
  17.         findViewById(R.id.btn_send_notification_with_tag).setOnClickListener(this); 
  18.         findViewById(R.id.btn_remove_notification_with_tag).setOnClickListener(this); 
  19.         findViewById(R.id.btn_send_ten_notification).setOnClickListener(this); 
  20.         findViewById(R.id.btn_send_flag_no_clear_notification).setOnClickListener(this); 
  21.         findViewById(R.id.btn_send_flag_ongoing_event_notification).setOnClickListener(this); 
  22.         findViewById(R.id.btn_send_flag_auto_cancecl_notification).setOnClickListener(this); 
  23.  
  24.         mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); 
  25.     } 
  26.  
  27.     @Override 
  28.     public void onClick(View v) { 
  29.         switch (v.getId()) { 
  30.             case R.id.btn_remove_all_notification: 
  31.                 //移除当前 Context 下所有 Notification,包括 FLAG_NO_CLEAR 和 FLAG_ONGOING_EVENT 
  32.                 mNotificationManager.cancelAll(); 
  33.                 break; 
  34.             case R.id.btn_send_notification: 
  35.                 //发送一个 Notification,此处 ID = 1 
  36.                 sendNotification(); 
  37.                 break; 
  38.             case R.id.btn_remove_notification: 
  39.                 //移除 ID = 1 的 Notification,注意:该方法只针对当前 Context。 
  40.                 mNotificationManager.cancel(DEFAULT_NOTIFICATION_ID); 
  41.                 break; 
  42.             case R.id.btn_send_notification_with_tag: 
  43.                 //发送一个 ID = 1 并且 TAG = littlejie 的 Notification 
  44.                 //注意:此处发送的通知与 sendNotification() 发送的通知并不冲突 
  45.                 //因为此处的 Notification 带有 TAG 
  46.                 sendNotificationWithTag(); 
  47.                 break; 
  48.             case R.id.btn_remove_notification_with_tag: 
  49.                 //移除一个 ID = 1 并且 TAG = littlejie 的 Notification 
  50.                 //注意:此处移除的通知与 NotificationManager.cancel(int id) 移除通知并不冲突 
  51.                 //因为此处的 Notification 带有 TAG 
  52.                 mNotificationManager.cancel(NOTIFICATION_TAG, DEFAULT_NOTIFICATION_ID); 
  53.                 break; 
  54.             case R.id.btn_send_ten_notification: 
  55.                 //连续发十条 Notification 
  56.                 sendTenNotifications(); 
  57.                 break; 
  58.             case R.id.btn_send_flag_no_clear_notification: 
  59.                 //发送 ID = 1, flag = FLAG_NO_CLEAR 的 Notification 
  60.                 //下面两个 Notification 的 ID 都为 1,会发现 ID 相等的 Notification 会被***的替换掉 
  61.                 sendFlagNoClearNotification(); 
  62.                 break; 
  63.             case R.id.btn_send_flag_auto_cancecl_notification: 
  64.                 sendFlagOngoingEventNotification(); 
  65.                 break; 
  66.             case R.id.btn_send_flag_ongoing_event_notification: 
  67.                 sendFlagAutoCancelNotification(); 
  68.                 break; 
  69.         } 
  70.     } 
  71.  
  72.     /** 
  73.      * 发送最简单的通知,该通知的ID = 1 
  74.      */ 
  75.     private void sendNotification() { 
  76.         //这里使用 NotificationCompat 而不是 Notification ,因为 Notification 需要 API 16 才能使用 
  77.         //NotificationCompat 存在于 V4 Support Library 
  78.         NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  79.                 .setSmallIcon(R.mipmap.ic_launcher) 
  80.                 .setContentTitle("Send Notification"
  81.                 .setContentText("Hi,My id is 1"); 
  82.         mNotificationManager.notify(DEFAULT_NOTIFICATION_ID, builder.build()); 
  83.     } 
  84.  
  85.     /** 
  86.      * 使用notify(String tag, int id, Notification notification)方法发送通知 
  87.      * 移除对应通知需使用 cancel(String tag, int id) 
  88.      */ 
  89.     private void sendNotificationWithTag() { 
  90.         NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  91.                 .setSmallIcon(R.mipmap.ic_launcher) 
  92.                 .setContentTitle("Send Notification With Tag"
  93.                 .setContentText("Hi,My id is 1,tag is " + NOTIFICATION_TAG); 
  94.         mNotificationManager.notify(NOTIFICATION_TAG, DEFAULT_NOTIFICATION_ID, builder.build()); 
  95.     } 
  96.  
  97.     /** 
  98.      * 循环发送十个通知 
  99.      */ 
  100.     private void sendTenNotifications() { 
  101.         for (int i = 0; i < 10; i++) { 
  102.             NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  103.                     .setSmallIcon(R.mipmap.ic_launcher) 
  104.                     .setContentTitle("Send Notification Batch"
  105.                     .setContentText("Hi,My id is " + i); 
  106.             mNotificationManager.notify(i, builder.build()); 
  107.         } 
  108.     } 
  109.  
  110.     /** 
  111.      * 设置FLAG_NO_CLEAR 
  112.      * 该 flag 表示该通知不能被状态栏的清除按钮给清除掉,也不能被手动清除,但能通过 cancel() 方法清除 
  113.      * Notification.flags属性可以通过 |= 运算叠加效果 
  114.      */ 
  115.     private void sendFlagNoClearNotification() { 
  116.         NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  117.                 .setSmallIcon(R.mipmap.ic_launcher) 
  118.                 .setContentTitle("Send Notification Use FLAG_NO_CLEAR"
  119.                 .setContentText("Hi,My id is 1,i can't be clear."); 
  120.         Notification notification = builder.build(); 
  121.         //设置 Notification 的 flags = FLAG_NO_CLEAR 
  122.         //FLAG_NO_CLEAR 表示该通知不能被状态栏的清除按钮给清除掉,也不能被手动清除,但能通过 cancel() 方法清除 
  123.         //flags 可以通过 |= 运算叠加效果 
  124.         notification.flags |= Notification.FLAG_NO_CLEAR; 
  125.         mNotificationManager.notify(DEFAULT_NOTIFICATION_ID, notification); 
  126.     } 
  127.  
  128.     /** 
  129.      * 设置FLAG_AUTO_CANCEL 
  130.      * 该 flag 表示用户单击通知后自动消失 
  131.      */ 
  132.     private void sendFlagAutoCancelNotification() { 
  133.         //设置一个Intent,不然点击通知不会自动消失 
  134.         Intent resultIntent = new Intent(this, MainActivity.class); 
  135.         PendingIntent resultPendingIntent = PendingIntent.getActivity( 
  136.                 this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
  137.         NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  138.                 .setSmallIcon(R.mipmap.ic_launcher) 
  139.                 .setContentTitle("Send Notification Use FLAG_AUTO_CLEAR"
  140.                 .setContentText("Hi,My id is 1,i can be clear."
  141.                 .setContentIntent(resultPendingIntent); 
  142.         Notification notification = builder.build(); 
  143.         //设置 Notification 的 flags = FLAG_NO_CLEAR 
  144.         //FLAG_AUTO_CANCEL 表示该通知能被状态栏的清除按钮给清除掉 
  145.         //等价于 builder.setAutoCancel(true); 
  146.         notification.flags |= Notification.FLAG_AUTO_CANCEL; 
  147.         mNotificationManager.notify(DEFAULT_NOTIFICATION_ID, notification); 
  148.     } 
  149.  
  150.     /** 
  151.      * 设置FLAG_ONGOING_EVENT 
  152.      * 该 flag 表示发起正在运行事件(活动中) 
  153.      */ 
  154.     private void sendFlagOngoingEventNotification() { 
  155.         NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
  156.                 .setSmallIcon(R.mipmap.ic_launcher) 
  157.                 .setContentTitle("Send Notification Use FLAG_ONGOING_EVENT"
  158.                 .setContentText("Hi,My id is 1,i can't be clear."); 
  159.         Notification notification = builder.build(); 
  160.         //设置 Notification 的 flags = FLAG_NO_CLEAR 
  161.         //FLAG_ONGOING_EVENT 表示该通知通知放置在正在运行,不能被手动清除,但能通过 cancel() 方法清除 
  162.         //等价于 builder.setOngoing(true); 
  163.         notification.flags |= Notification.FLAG_ONGOING_EVENT; 
  164.         mNotificationManager.notify(DEFAULT_NOTIFICATION_ID, notification); 
  165.     }     
  166.  

给Notification设置PendingIntent

PendingIntent可以通过setContentIntent(PendingIntent intent)这个方法进行设置

当我们点击通知栏时想跳转一个Activity或者开启一个service时,就可以通过设置PendingIntent达成

PendingIntent 是 Android 系统管理并持有的用于描述和获取原始数据的对象的标志(引用)。也就是说,即便创建该PendingIntent对象的进程被杀死了,这个PendingItent对象在其他进程中还是可用的。

日常使用中的短信、闹钟等都用到了 PendingIntent。

PendingIntent 主要可以通过以下三种方式获取:

  1. //获取一个用于启动 Activity 的 PendingIntent 对象 
  2. public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags); 
  3.  
  4. //获取一个用于启动 Service 的 PendingIntent 对象 
  5. public static PendingIntent getService(Context context, int requestCode, Intent intent, int flags); 
  6.  
  7. //获取一个用于向 BroadcastReceiver 广播的 PendingIntent 对象 
  8. public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)  

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 。

自定义Notification

Android系统允许使用RemoteViews来自定义通知。自定义普通视图通知高度限制为64dp,大视图通知高度限制为256dp。同时,建议自定义通知尽量简单,以提高兼容性。

自定义通知需要做如下操作:1、创建自定义通知布局2、使用RemoteViews定义通知组件,如图标、文字等3、调用setContent()将RemoteViews对象绑定到NotificationCompat.Builder4、同正常发送通知流程

注意: 避免为通知设置背景,因为兼容性原因,有些文字可能看不清。

关于自定义Notification兼容问题,请阅读我的另一篇博客 Android通知栏版本兼容解决方案

例子:

  1. RemoteViews notifactionView = new RemoteViews(mContext.getPackageName(), 
  2.         R.layout.cl_screen_notification); 
  3. mBuilder.setContent(notifactionView); 
  4. notifactionView.setOnClickPendingIntent(R.id.cl_screen_notification, pendingIntent); 
  5. Bitmap pluginIcon = drawableToBitmap(pluginDrawable); 
  6. LogUtils.d("myl""获得icon" + pluginIcon); 
  7. notifactionView.setImageViewBitmap(R.id.cl_plugin_icon, pluginIcon); 
  8. notifactionView.setTextViewText(R.id.dl_plugin_msg, pluginContent); 
  9. Notification notification = mBuilder.build(); 
  10. int id = 199; 
  11. LogUtils.d(TAG, "创建通知"); 
  12. mNotificationManager.notify(id, notification);  

Notification的各种样式

1) BigText样式(Android 4.1以上)

a) ***高度一般为256dp

b) 不是***的通知时默认为折叠状态

c) 不设置SummaryText的话,展开后最下面一行的内容会消失

例子:

  1. private void showBigViewText() { 
  2.          NotificationCompat.BigTextStyle textStyle = new BigTextStyle(); 
  3.          textStyle 
  4.                  .setBigContentTitle("BigContentTitle"
  5.                  .setSummaryText("SummaryText"
  6.                  .bigText( 
  7.                          "I am Big Text"); 
  8.          Notification notification = new NotificationCompat.Builder(context) 
  9.                  .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher) 
  10.                  .setTicker("showBigView_Text").setContentInfo("contentInfo"
  11.                  .setContentTitle("ContentTitle").setContentText("ContentText"
  12.                  .setStyle(textStyle) 
  13.                  .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL) 
  14.                  .build(); 
  15.          manager.notify(NOTIFICATION_ID_2, notification); 
  16.      }  

2) Inbox样式

a) 高度一般为256dp

b) 不是***的通知时默认为折叠状态

c) 不设置SummaryText的话,展开后最下面一行的内容会消失

例子:

  1. private void showBigViewInbox() { 
  2.         NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); 
  3.         inboxStyle.setBigContentTitle("BigContentTitle").setSummaryText( 
  4.                 "SummaryText"); 
  5.         for (int i = 0; i < 5; i++) 
  6.             inboxStyle.addLine("news:" + i); 
  7.         Notification notification = new NotificationCompat.Builder(context) 
  8.                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher) 
  9.                 .setTicker("showBigView_Inbox").setContentInfo("contentInfo"
  10.                 .setContentTitle("ContentTitle").setContentText("ContentText"
  11.                 .setStyle(inboxStyle) 
  12.                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL) 
  13.                 .build(); 
  14.         manager.notify(NOTIFICATION_ID_4, notification); 
  15.     }  

3) BigPicture样式

a) 高度一般为256dp

b) 不是***的通知时为默认折叠状态

c) 不设置SummaryText的话,展开后第二行字的内容会消失

例子:

  1. private void showBigViewPic() { 
  2.          NotificationCompat.BigPictureStyle pictureStyle = new BigPictureStyle(); 
  3.          pictureStyle.setBigContentTitle("BigContentTitle"
  4.                  .setSummaryText("SummaryText").bigPicture(icon); 
  5.          Notification notification = new NotificationCompat.Builder(context) 
  6.                  .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher) 
  7.                  .setTicker("showBigView_Pic").setContentInfo("contentInfo"
  8.                  .setContentTitle("ContentTitle").setContentText("ContentText"
  9.                  .setStyle(pictureStyle) 
  10.                  .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL) 
  11.                  .build(); 
  12.          manager.notify(NOTIFICATION_ID_3, notification); 
  13.      }  

4) 折叠式Notification

折叠式Notification是一种自定义视图的Notification,用来显示长文本和一些自定义的布局的场景。它有两种状态,一种是普通状态下的视图,一种是展开状态下的视图。和普通Notification不同的是,我们需要自定义的视图,而这个视图显示的进程和我们创建视图的进程不再一个进程,所以我们需要使用RemoteViews,首先要使用RemoteViews来创建我们的自定义视图:

  1. //用RemoteViews来创建自定义Notification视图 
  2. RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.view);  

视图的布局文件:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="100dp" 
  5.     android:background="@drawable/fold" 
  6.     android:orientation="horizontal"
  7. <ImageView 
  8.     android:id="@+id/iv_image" 
  9.     android:layout_width="100dp" 
  10.     android:layout_height="100dp" 
  11.     android:src="@drawable/fold" 
  12.     /> 
  13.  
  14.     <TextView 
  15.         android:id="@+id/tv_text" 
  16.         android:layout_width="wrap_content" 
  17.         android:layout_height="wrap_content" 
  18.         android:layout_marginTop="30dp" 
  19.         android:layout_marginLeft="150dp" 
  20.         android:text="展开后的视图" 
  21.         android:textColor="@color/colorPrimaryDark"/> 
  22. </LinearLayout>  

把自定义视图赋值给Notification展开时的视图

  1. //指定展开时的视图 
  2. notification.bigContentView = remoteViews;  

也可以把自定义视图赋值给Notification普通状态时的视图

  1. //指定普通状态时的视图 
  2. notification.contentView = remoteViews;  

折叠式Notification完整代码:

  1. Notification.Builder builder = new Notification.Builder(this); 
  2.        Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/itachi85/")); 
  3.        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0); 
  4.        builder.setContentIntent(pendingIntent); 
  5.        builder.setSmallIcon(R.drawable.foldleft); 
  6.        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher)); 
  7.        builder.setAutoCancel(true); 
  8.        builder.setContentTitle("折叠式通知"); 
  9.        //用RemoteViews来创建自定义Notification视图 
  10.        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.view_fold); 
  11.        Notification notification = builder.build(); 
  12.        //指定展开时的视图 
  13.        notification.bigContentView = remoteViews; 
  14.        notificationManager.notify(1, notification);  

5) 悬挂式Notification (5.0新增)

悬挂式Notification是android5.0新增加的方式,悬挂式Notification不需要下拉通知栏就直接显示出来悬挂在屏幕上方并且焦点不变仍在用户操作的界面因此不会打断用户的操作,过几秒就会自动消失。他需要调用setFullScreenIntent来将Notification变为悬挂式Notification

  1. //如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的 
  2.         PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT); 
  3.         builder.setFullScreenIntent(hangPendingIntent, true);  

悬挂式Notification完整代码:

  1. Notification.Builder builder = new Notification.Builder(this); 
  2.         Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.csdn.net/itachi85/")); 
  3.         PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0); 
  4.         builder.setContentIntent(pendingIntent); 
  5.         builder.setSmallIcon(R.drawable.foldleft); 
  6.         builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher)); 
  7.         builder.setAutoCancel(true); 
  8.         builder.setContentTitle("悬挂式通知"); 
  9.         //设置点击跳转 
  10.         Intent hangIntent = new Intent(); 
  11.         hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
  12.         hangIntent.setClass(this, MyNotificationActivity.class); 
  13.         //如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的 
  14.         PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT); 
  15.         builder.setFullScreenIntent(hangPendingIntent, true); 
  16.         notificationManager.notify(2, builder.build());   

 

 

 

6) 锁屏通知

Android 5.0(API level 21)开始,通知可以显示在锁屏上。用户可以通过设置选择是否允许敏感的通知内容显示在安全的锁屏上。你的应用可以通过setVisibility()控制通知的显示等级:

VISIBILITY_PRIVATE : 显示基本信息,如通知的图标,但隐藏通知的全部内容

VISIBILITY_PUBLIC : 显示通知的全部内容

VISIBILITY_SECRET : 不显示任何内容,包括图标

  1. builder.setVisibility(Notification.VISIBILITY_PUBLIC);  
责任编辑:庞桂玉 来源: Android开发中文站
相关推荐

2011-07-07 08:49:14

iPhone Push Notificati

2010-03-09 17:19:01

Linux时钟

2010-07-22 09:25:09

telnet命令

2010-06-24 15:35:04

IPx协议

2010-09-25 14:12:50

Java内存分配

2012-11-15 13:42:29

2017-05-23 15:47:04

JavaScriptthis解析

2010-08-04 14:34:35

Flex编程模型

2016-03-24 14:02:05

ActivityAndroid启动

2009-12-25 16:47:04

Linux Make规

2009-01-12 10:27:07

IT职位解析认证

2010-03-08 17:27:56

Linux profi

2010-10-20 15:11:53

SQL Server作

2009-11-11 17:02:44

MPLS路由协议

2010-09-17 10:04:36

2009-07-06 09:17:51

2010-01-06 17:12:57

Linux主要构成

2010-06-28 18:52:49

UML关系符号

2021-11-23 09:09:27

Applicationandroid系统开发

2009-10-19 15:07:17

Visual Basi
点赞
收藏

51CTO技术栈公众号