这次主要用Notification和NotificationManager实现了Android通知栏发通知的功能。以下是主要的方法:
获取NotificationManager
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
初始化Notification
我们先初始化一个Notification,是在未下拉时通知栏显示的效果:
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.defaults = Notification.DEFAULT_ALL;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.tickerText="我是个消息";
notification.when = System.currentTimeMillis();
/**
* notification.defaults = Notification.DEFAULT_SOUND; 默认声音
* 使用自定义声音 notification.sound = Uri.parse(uriString);
*
* notification.defaults = Notification.DEFAULT_LIGHTS; 默认闪光灯
* 权限:<uses-permission android:name="android.permission.FLASHLIGHT" />
* notification.ledARGB = 0xff00ff00; 颜色
* notification.ledOnMS = 300; //亮的时间
* notification.ledOffMS = 1000; //灭的时间
*
* notification.defaults = Notification.DEFAULT_VIBRATE; 默认震动
* 权限:<uses-permission android:name="android.permission.VIBRATE" />
* long[] vibrate = {0,100,200,300};
* notification.vibrate = vibrate; 震动的时间
*/
/**
* notification.flags |= Notification.FLAG_AUTO_CANCEL;自动取消
* 其他属性:
* Notification.FLAG_INSISTENT; //让声音、振动无限循环,直到用户响应
* Notification.FLAG_AUTO_CANCEL; //通知被点击后,自动消失
* Notification.FLAG_NO_CLEAR; //点击'Clear'时,不清楚该通知
*/
/**
* notification.tickerText 标题
* notification.when 提醒时间
*/
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(
MainActivity.this, requestCode, intent, flags);
notification.contentIntent = pIntent;
notification.setLatestEventInfo(MainActivity.this, "我改的标题","我改的内容", pIntent);
/**
* intent 点击通知时的意图
* notification.setLatestEventInfo 下拉状态时显示的效果
* pendingIntent中的flag:
* * 0:不带数据
* PendingIntent.FLAG_CANCEL_CURRENT:最后一次有效
* PendingIntent.FLAG_UPDATE_CURRENT:描述的Intent有 更新的时候需要用到这个flag去更新你的描述,否则组件在下次事件发生或时间到达的时候extras永远是第一次Intent的extras
* PendingIntent.FLAG_ONE_SHOT:PendingIntent只能使用一次
* PendingIntent.FLAG_NO_CREATE:利用FLAG_NO_CREAT获取的PendingIntent,若描述的Intent不存在则返回NULL值
*
*/
最后显示通知:
manager.notify(id, notification);
当然可以通过id取消通知
manager.cancel(id);
manager.cancelAll();