Android Notifications

当一个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可以根据id号确定是哪个notification,在更新notification时,如果id号一致,那么新的

notification会替代旧的activity,如果id号不一致,那么将在通知栏显示两个图标。

即即使在一个应用中通知栏图标的个数与id号的个数是一致的。





为notification添加声音震动等
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值