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 and contentText 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 a
RemoteViews
object that inflates a custom layout file, then pass the
RemoteViews
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中定義的,是以需要什麼樣式都可以了。