Android开发学习之添加StatusBarNotification(状态栏通知)

来源:互联网 发布:火狐淘宝无法登陆 编辑:程序博客网 时间:2024/06/01 08:47
1.StatusBarNotification介绍
顾名思义,就是对状态栏的一些操作。当我们执行一个操作,想在状态栏上给出提示时,就是这里想要实现的功能。比如未接电话,未读过的短信,文件下载等等... ...
2.分析:
这里要涉及到3个东西:PendingIntent,Notification,NotificationManager。
(1)PendingIntent 即将发生的Intent,其实就是状态栏拉下来以后供点击的几个选项。这里就牵涉到好几个问题,与下面函数中的参数一一对应起来。
PendingIntent.getActivity (Context context, int requestCode, Intent intent, int flags)
contenxt一般是切换至intent的Activity;
requestCode一般取0;
intent是已经设置好切换Activity的intent(这里的Activity要setClass设置好切换的Activity);
flags有4个选项,一般选PendingIntent.FLAG_UPDATE_CURRENT。
(2)Notification 设置好的一些通知的信息,以及通知的方式等等
Notification notification = newNotification(icon, tickerText,when)
icon是状态栏上的图标,我们可以把相应的图片放在drawble文件夹下,这时系统会自动为图片文件添加一个id,我们只要使用R.drawable.xxx就行了;
tickerText是状态栏上通知的文字信息;
when是什么时候给出通知,一般使用System.currentTimeMillis()获取当前时间。
注:
notification.flags = Notification.FLAG_NO_CLEAR(图标无法清除,QQ就是这样实现的)
notification.flags = Notification.FLAG_AUTO_CANCEL(点击后自动清除);
(3)NotificationManager 管理状态栏的一个类
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, notification); //给出通知
notificationManager.cancel(id); //取消通知
3.一个例子
代码:
MainActivity.java
点击按钮的onClick()方法中相应的操作:
Intent intent = new Intent(MainActivity.this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, intent , PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification(R.drawable.notification_icon, "小石头上线", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(MainActivity.this, "QQ", "小石头上线", contentIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
效果:
Android开发学习之添加StatusBarNotification(状态栏通知)
Android开发学习之添加StatusBarNotification(状态栏通知)
0 1
原创粉丝点击