Android使用通知(Notification)

一、通知(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,表示最高的程度,效果如下
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值