通知用法:1.在活动里创建;2.在广播接收器里创建;3.在服务里创建
步骤:
1.通过NotificationManager来对通知进行管理,调用Context的getSystemService()方法获取到(参数为Context.NOTIFICATION_SERVICE);
2.创建一个Notification对象。参数一:指定通知的图标;参数二:指定通知ticker内容;参数三:指定通知被创建的时间,以毫秒为单位
3.对通知的布局进行设定,调用Notification的setLatestEventInfo()方法来设置。参数一:Context;参数二:标题内容;参数三:正文内容;参数四:点击事件
4.设置点击效果,PendingIntent,可根据需求使用getActivity()、getBroadcast()、getService()方法获取。参数一:Context;参数二:0;参数三:Intent对象;参数四:PendingItent的行为
5.显示通知,调用NotificationManager的notify()方法。参数一:id,每个通知所指定的id是唯一的;参数二:Notification对象
NotificationManager mamager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "This is ticker text",System.currentTimeMillis());
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(this, "This is content title", "This is content text", pi);
mamager.notify(1, notification);
6.使通知消失
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);
想要取消哪一条通知,就在cancel()方法中传入该通知的id
高级技巧
1.音频
Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/...."));
notification.sound = soundUri;
2.震动
long[] vibrates = {0, 1000, 1000, 1000};
notification.vibrate = vibrates;
下标为0: 表示手机静止时常。下标为1:表示手机震动时常。依次类推
权限:<uses-permission android:name="android.permission.VIBRATE"/>
3.LED灯
notification.ledARGB = 0xFF0000;
notification.ledOnMS = 1000;
notification.ledOffMS = 1000;
notification.flags = Notification.FLAG_SHOW_LIGHTS;
也可以默认设置,会根据手机的具体环境来设置
notification.defaults = Notification.FLAG_SHOW_LIGHTS;