android开发之Notification

Notification简介

  Notification看名字就知道,是一个和提醒有关的东西,它通常和NotificationManager一块使用。具体来说,其主要功能如下。

  1.NotificationManager和Notification用来设置通知

  通知的设置等操作相对比较简单,基本的使用方式就是新建一个Notification对象,设置好通知的各项参数,然后使用系统后台运行的NotificationManager服务将通知发出来。基本步骤如下。

  1)得到NotificationManager,代码如下。

   String  ns  =  Context.NOTIFICATION_SERVICE;

  NotificationManager mNotificationManager 
=  (NotificationManager) getSystemService(ns);

  2)创建一个新的Notification对象,代码如下。

  Notification notification  =   new  Notification();

  notification.icon 
=  R.drawable.notification_icon;

  也可以使用稍微复杂一些的方式创建Notification,代码如下。

   int  icon  =  R.drawable.notification_icon;  // 通知图标

  CharSequence tickerText 
=   " Hello " // 状态栏(Status Bar)显示的通知文本提示

  
long  when  =  System.currentTimeMillis();  // 通知产生的时间,会在通知信息里显示

  Notification notification 
=   new  Notification(icon, tickerText, when);

  3)填充Notification的各个属性,代码如下。

  Context context  =  getApplicationContext();

  CharSequence contentTitle 
=   " My notification " ;

  CharSequence contentText 
=   " Hello World! " ;

  Intent notificationIntent 
=   new  Intent(this, MyClass.class);

  PendingIntent contentIntent 
=  PendingIntent.getActivity(this,  0 , notificationIntent,  0 );

  notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

  Notification提供了如下几种手机提示方式。

  状态栏(Status Bar)显示的通知文本提示,例如:

  notification.tickerText = "hello";

  发出提示音,例如:

  notification.defaults | =  Notification.DEFAULT_SOUND;

  notification.sound 
=  Uri.parse( " file:///sdcard/notification/ringer.mp3 " );

  notification.sound 
=  Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI,  " 6 " );

  手机振动,例如:

  notification.defaults | =  Notification.DEFAULT_VIBRATE;

  
long [] vibrate  =  { 0 , 100 , 200 , 300 };

  notification.vibrate 
=  vibrate;

  LED灯闪烁,例如:

  notification.defaults | =  Notification.DEFAULT_LIGHTS;

  notification.ledARGB 
=  0xff00ff00;

  notification.ledOnMS 
=   300 ;

  notification.ledOffMS 
=   1000 ;

  notification.flags |
=  Notification.FLAG_SHOW_LIGHTS;

  4)发送通知,代码如下。

   private  static final  int  ID_NOTIFICATION  =   1 ;

  mNotificationManager.notify(ID_NOTIFICATION, notification);

  2.更新通知

  如果需要更新一个通知,只需要在设置好Notification之后,再调用setLatestEventInfo,然后重新发送一次通知即可。

  为了更新一个已经触发过的Notification,传入相同的ID。用户既可以传入相同的Notification对象,也可以是一个全新的对象。只要ID相同,新的Notification对象会替换状态条图标和扩展的状态窗口的细节。

  另外,还可以使用ID来取消Notification,通过调用NotificationManager的cancel方法,代码如下。

  notificationManager.cancel(notificationRef);

  当取消一个Notification时,会移除它的状态条图标以及清除在扩展的状态窗口中的信息。

你可能感兴趣的:(java,android)