当一个service需要用户对一个事件发生响应时,需要用
一个Notification提醒用户,而不是直接打开一个activity
在notification window中会显示notification的扩展信息
一个activity和service可以初始化一个notification,
由于activity只有在可视状态下才会执行操作,因此一个notification常常是由service产生的
创建一个notification必需使用两个类,Notification
和NotificationManager
用Notification的一个实例定义notification的图标、信息、
声音等,NotificationManager是android提供的系统服务,
负责执行和管理所有的Notification,不需要实例化NotificationManger,需要 使用getSystemService()方法
获得NotificationManager的引用
创建通知栏的步骤
1、获得NotificationManager引用
NotificationManager manager = (NotificationManager )
getSystemService(Context.NOTIFICATION_SERVICE);
2、实例化Notification
int icon = R.drawable.ic_lanucher;
String showText = "hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon,showText,when);
3、定义扩展信息和Intent
Context context = getApplicationContext();
String contentTitle = "my notification";
String contentText = "hello ,world";
Intent notificationInten = new Intent(this,GridActivity.class);
PendingIntent contentIntent = PendingInten.getActivity(this,0,notificationInten,0);
notification.setLatestEventInfo(context,contentTitle,contentText,contentIntent);
4、将notification传递给NotificationManager
manager.notify(1,notification);
这里的1代表notification的id号,如果一个应用里包含多个
为notification添加声音震动等
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
一个Notification提醒用户,而不是直接打开一个activity
在notification window中会显示notification的扩展信息
一个activity和service可以初始化一个notification,
由于activity只有在可视状态下才会执行操作,因此一个notification常常是由service产生的
创建一个notification必需使用两个类,Notification
和NotificationManager
用Notification的一个实例定义notification的图标、信息、
声音等,NotificationManager是android提供的系统服务,
负责执行和管理所有的Notification,不需要实例化NotificationManger,需要 使用getSystemService()方法
获得NotificationManager的引用
创建通知栏的步骤
1、获得NotificationManager引用
NotificationManager manager = (NotificationManager )
getSystemService(Context.NOTIFICATION_SERVICE);
2、实例化Notification
int icon = R.drawable.ic_lanucher;
String showText = "hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon,showText,when);
3、定义扩展信息和Intent
Context context = getApplicationContext();
String contentTitle = "my notification";
String contentText = "hello ,world";
Intent notificationInten = new Intent(this,GridActivity.class);
PendingIntent contentIntent = PendingInten.getActivity(this,0,notificationInten,0);
notification.setLatestEventInfo(context,contentTitle,contentText,contentIntent);
4、将notification传递给NotificationManager
manager.notify(1,notification);
这里的1代表notification的id号,如果一个应用里包含多个
notification可以根据id号确定是哪个notification,在更新notification时,如果id号一致,那么新的
notification会替代旧的activity,如果id号不一致,那么将在通知栏显示两个图标。
即即使在一个应用中通知栏图标的个数与id号的个数是一致的。
为notification添加声音震动等
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;