NotificationManager 通知

来源:互联网 发布:夏普比率算法 编辑:程序博客网 时间:2024/06/05 14:16

通知管理器NotificationManager用
通知Notification 和 NotificationManager用法

NotificationManager(通知管理器)
lNotificationManager(通知管理器):
NotificationManager负责通知用户事件的发生.
NotificationManager有三个公共方法:
1. cancel(int id) 取消以前显示的一个通知.假如是一个短暂的通知,试图将隐藏,假如是一个持久的通知,将从状态条中移走.
2. cancelAll() 取消以前显示的所有通知.
3. notify(int id, Notification notification) 把通知持久的发送到状态条上.
//初始化NotificationManager:
NotificationManager nm =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification的属性
audioStreamType 当声音响起时,所用的音频流的类型
contentIntent 当通知条目被点击,就执行这个被设置的Intent.
contentView 当通知被显示在状态条上的时候,同时这个被设置的视图被显示.
defaults 指定哪个值要被设置成默认的.
deleteIntent 当用户点击”Clear All Notifications”按钮区删除所有的通知的时候,这个被设置的Intent被执行.
icon 状态条所用的图片.
iconLevel 假如状态条的图片有几个级别,就设置这里.
ledARGB LED灯的颜色.
ledOffMS LED关闭时的闪光时间(以毫秒计算)
ledOnMS LED开始时的闪光时间(以毫秒计算)
number 这个通知代表事件的号码
sound 通知的声音
tickerText 通知被显示在状态条时,所显示的信息
vibrate 振动模式.
when 通知的时间戳.
发送一个通知的实例
1.获得NotificationManager
NotificationManager manager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE);
2. // 创建一个Notification
Notification notification = new Notification();
// 设置显示在手机最上边的状态栏的图标
notification.icon = R.drawable.ic_action_search;
// 当当前的notification被放到状态栏上的时候,提示内容
notification.tickerText = “注意了,我被扔到状态栏了”;
// 添加声音提示
notification.defaults=Notification.DEFAULT_SOUND;
// audioStreamType的值必须AudioManager中的值,代表着响铃的模式
notification.audioStreamType= android.media.AudioManager.ADJUST_LOWER;
Intent intent = new Intent(this, Notification2Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
// 点击状态栏的图标出现的提示信息设置
notification.setLatestEventInfo(this, “内容提示:”, “我就是一个测试文件”, pendingIntent);
manager.notify(1, notification);
PendingIntent
lPendingIntent:
里面有三个方法:
1. PendingIntent.getActivity () 当点击通知信息时开始一个新的activity
2. PendingIntent. getBroadcast() 当点击通知信息时开始一个新的广播
3. PendingIntent. getService () 当点击通知信息时开始一个新的服务
Notification提供了丰富的手机提示方式
a)在状态栏(Status Bar)显示的通知文本提示,如:
notification.tickerText = “hello”;
b)发出提示音,如:
notification.defaults = Notification.DEFAULT_SOUND;
notification.sound = Uri.parse(“file:///sdcard/notification/ringer.mp3”);
notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, “6”);
c)手机振动,如:
notification.defaults = Notification.DEFAULT_VIBRATE;
long[] vibrate = {0,100,200,300};
notification.vibrate = vibrate;//当手机震动时,震动周期设置
d)LED灯闪烁,如:
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.ledARGB = 0xff00ff00; // LED灯的颜色,绿灯
notification.ledOnMS = 300; // LED灯显示的毫秒数,300毫秒
notification.ledOffMS = 1000; // LED灯关闭的毫秒数,1000毫秒
notification.flags = Notification.FLAG_SHOW_LIGHTS; // 必须加上这个标志