原文出处:http://blog.csdn.net/q384415054/article/details/8076556
1.Notification介绍
Notification通过NotificationManager可以往状态栏中发送通知。
在API Level 11之前构造一个Notification如下:
大致过程:
1.实例化一个Notification对象notify
2.给notify赋值,从icon到notify.setLatestEventInfo()
3.用NotificationMnager将notify发送出去
下面来看下setLatestEventInfo()这个被废弃的方法。
从源码中可以看出,setLatestEventInfo()这个方法内部会实例化一个RemoteViews对象再将
通知标题contentTitle和通知内容contentText用setTextVewText赋值给RemoteViews对象,在最后
this.contentView = contentView再将RemoteViews对象赋值给notification中字段contentView.
是不是这边有一种绕来绕去的感觉,是不是有点不干脆?
因为Notification中没有直接能设置通知标题和通知内容的方法,通知的标题和内容是在RemoteViews,因此需要先给RemoteViews
对象赋值再将RemoteViews对象给Notification.
在API Level 11之后,Notification引入了一个内部类Builder,将原来这种方法改变了。现在这个Builder提供构造一个Notification的所有的要素,所以setLatestEventInfo()就被废弃了。这样设计更加合理也更加简单容易理解。
当然以前的方法还是可以用的,就是直接给Notification对象的字段赋值。
在新的版本中废弃的方法最好还是不要用了。
2.自定义Notification
下面来一段API中的介绍:
By default, the notification that appears in the notifications window includes a title and the message text. These are defined by thecontentTitle andcontentText parameters of the setLatestEventInfo()
method. However, you can also define a custom layout for the notification using RemoteViews
.
To define your own layout for the notification, instantiate aRemoteViews
object that inflates a custom layout file, then pass theRemoteViews
to thecontentView field of your Notification.
一般来说,出现在通知窗口中的通知都包含标题和内容。这些都是在setLatestEventInfo()中的两个参数thecontentTitle and contentText所定义的。然而你也可以用RemoteViews给Notification进行自定义的布局。
要定义自己的Notification布局,要实例化一个RemoteViews对象,该对象需要引入一个自定义的布局文件,然后将该RemoteViews对象赋值给Notification中的contentView字段。
或者用builder来设置也可以。
builder.setContent(views);
因为这个R.layout.self_layout是自己在xml中定义的,所以需要什么样式都可以了。