android 详解Notification


Notification作为一个事件触发通知型的交互提示接口,在消息提示方面给了我们很好的交互体验。


Google在Android5.0中又进一步改进了通知栏,优化了Notification。在长按Notification时,会显示消息的来源。


1。先来讲解一下最基本的Notification,此时的Notification的创建已经摒弃了new Notification的做法,而是使用了Notification.Builder来创建一个Notification的builder

   Notification.Builder builder=new Notification.Builder(this);


是不是与AlertDialog的使用方法类似,他们使用的都是Builder模式来创建对象。


接下来如果想要点击Notification后执行某个Intent,则需要PendingIntent。PendingIntent的使用也是比较简单的,只需要在普通Intent上包装一层就可以了。

Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));
PendingIntent pendingIntent =PendingIntent.getActivity(this,0,intent,0);

这样就可以在点击Notification的时候触发PendingIntent事件了。

与使用AlertDialog一样,有了builder对象,就可以给他增加各种属性了。

builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher));
builder.setContentTitle("Basic Notification");
builder.setContentText("I am a basic notification");
builder.setSubText("it is really basic");


最后,通过NotificationManager来帮助我们管理Notification,并调用notify方法来发出Notification。

NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(1,builder.build());




2。折叠的Notification

 
折叠式的Notification是一种自定义视图的Notification,常常用于显示长文本。它拥有两种视图状态,一种是普通状态下的视图状态,另一种是展开状态的视图状态。


在Notification中,使用RemoteViews来帮助我们创建一个自定义的Notification视图。


RemoteViews contentView=new RemoteViews(getPackageName(),R.layout.notification);
Notification notification=builder.build();
notification.contentView=contentView;
RemoteViews expandView=new RemoteViews(getPackageName(),R.layout.notification_expand);
notification.bigContentView=expandView;


3.悬挂式Notification


悬挂式Notification是Android5.0中新增的方式,可以在屏幕上方产生Notification且不会打断用户操作。

前面代码一样,区别是:

builder.setContentText("I am a basic notification").setFullScreenIntent(pendingIntent,true);

通过setFullScreenIntent,就能轻松的将Notification变成悬挂式Notification。



4.显示等级的Notification



Android5.X中新加入了一种模式--Notification的显示等级。


<1> VISIBILITY_PRIVATE  表示只有当没有锁屏的时候显示。

<2> VISIBILITY_PUBLIC    表示在任何时候都会显示

<3> VISIBILITY_SECRET  表示在pin,password等安全锁和没有锁屏的情况下才能够显示。

设置方法非常的简单。同样需要借助builder对象。

builder.setVisibility(Notification.VISIBILITY_PUBLIC);

大概就是这些,剩下的希望广大网友进行建议和补充。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值