一、通知(Notification)是android中的功能,当某个应用程序希望向用户发出一些提示的消息,而该程序又不在前台运行,就可以借助通知来实现
用法比较灵活,可以在活动中创建,也可以在广播接收器中创建,也可以在服务中创建
1、首先需要一个Manager来管理,可以调用getSystemService()方法获取到,接收一个字符串参数用于确定获取系统的哪个服务,这里我们传入Context.NOTIFICATION_SERVICE
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
2、需要使用一个Builder构造器来创建Notification对象,几乎所有的android版本都会对通知这部分功能进行修改,所以使用v4包的NotificationCompat类创建对象,能保证在所有的版本上正常工作
Notification notification = new NotificationCompat.Builder(context).build();
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("this is content title")
.setContentText("this is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.small_icon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.large_icon))
.build();
3、调用manager.notify(1,notification);
接收两个参数,第一个是id,要保证每个通知所指定的id是不同的,第二个参数是Notifition对象
效果:
怎么实现通知可以点击——PendingIntent,与Intent(更倾向于立即执行某个动作)类似,但是其更倾向于在某个适合的时机去执行某个动作,可以简单理解为延迟执行的intent
用法:提供了三个方法,可以根据需求去选择使用,getActivity(),getBroadcast(),getService(),参数是一样的,第一个是Context,第二个参数一般用不到,0;第三个参数是Intent对象,第四个参数用于确定PendingIntent的行为,有五种值可以选择,通常情况这个传入0就可以了
新建一个活动
但是通知的图标没有消失
两种办法
(1)在NotificationCompat.Builder中
(2)在显示的调用NotificationManager的cancle()方法,其中1就是id号,就是取消哪个通知
二、通知的进一步使用
1、setSound()——播放音频
2、setVibrate(new long[]{0,1000,1000,1000})——震动(要申明权限)
3、setLights(Color.GREEN,1000,1000)
4、直接设置通知的默认效果,根据当前的手机环境来决定播放什么声音
setDefaults(NotificationCompat.DEFAULT_ALL)
5、设置长文字setStyle()方法,一般太长就会以省略号的形式进行忽略
setStyle(new NotificationCompat.BigTextStyle().bigText("Nowadays, the technology develops so fast that people " +
"use advanced technology to facilitate their lives, " +
"such as communicating with their friends and families any time. " +
"Technology makes the world smaller and some people have advocated to work at home by computers because of the advantages."))
6、设置通知的重要程度,
这里选择的是PRIORITY_MAX,表示最高的程度,效果如下