引言
首先推薦個我整理的Notification樣式
Notification 在v7版本下從4.0后增加了Media Style. 今天我們分析下Notification在v7版本的源碼。有助于我們針對不同版本的Notification做出合適樣式選擇。
Notification使用流程
現(xiàn)在我們使用Notification基本都是如下步驟:
- NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
- builder.setContentText
.setSmallIcon
.set... - Notification notification = builder.build();
- notificationManager.notify(TYPE_BigText,notification);
我們看一下涉及到的類定義:
NotificationCompat
Helper for accessing features in Notification introduced after API level 4 in a backwards compatible fashion.
幫助Notification存儲細(xì)節(jié)。
NotificationCompat.Builder
Builder class for NotificationCompat objects. Allows easier control over all the flags, as well as help constructing the typical notification layouts.
NotificationCompat對象的構(gòu)造器類,構(gòu)造Notification的樣式。
當(dāng)Notification構(gòu)建好之后最后一個步驟:
NotificationManager
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
推送一個Notification到狀態(tài)欄,如果應(yīng)用中已經(jīng)有了一個同樣的Notification Id 將會被代替并更新。
Android support v7中的Notification相關(guān)類
v7對v4中的Notification進(jìn)行擴(kuò)展。
v7下NotificationCompat的定義
然后我來看下NotificationCompat.Builder的定義
Builder重寫了v4下的getExtender() method,看下返回類型BuilderExtender 找到這樣的定義
Interface for appcompat to extend v4 builder with media style.
appcompat 用來擴(kuò)增v4 media style 的接口
我們再仔細(xì)看getExtender中的代碼,針對不同版本sdk,返回不同版本的BuilderExtender.
針對ICE_CREAM_SANDWICH版本的BuilderExtender的代碼看下:
內(nèi)部調(diào)用add方法進(jìn)行整理樣式
用table顯示不同版本擴(kuò)展mediastyle的method.
版本 | 整理樣式的方法
------------- | -------------| -------------
LOLLIPOP (>=Android 5.1) | addMediaStyleToBuilderLollipop
JELLY_BEAN (>=Android4.1&&<Android 5.1) | addMediaStyleToBuilderIcs
ICE_CREAM_SANDWICH (>=Android4.0&&<Android 4.1) | addBigMediaStyleToBuilderJellybean
<Android 4.0 | 使用v4里的樣式整理方法
從這個表格可以知道 4.0以后才出現(xiàn)的Media Style.
再看v4下Builder.build method
最終是通過BuilderExtender構(gòu)造Notification.
總結(jié)
- Builder構(gòu)造好樣式后,會根據(jù)不同版本生成不同的BuilderExtender.
- 如果你想知道Notification在不同版本上的限制,你只需要查看不同版本的BuilderExtender的區(qū)別即可。