Android自定義狀態欄通知(Status Notification)的正確實現
在Android應用開發中,經常會使用到狀態欄通知(Status Notification),例如新浪微博、網易新聞等提供的推送消息,軟件後台更新時進度的顯示等等,如下圖所示:
看了網上很多關於Notification的博客文章,發現幾乎沒有一個能將自定義狀態欄通知完全實現正確的,因此,本文就來說說實現自定義狀態欄通知經常被忽略的一些知識點。
1) 使用Notification最常見的場景
運行在後台的Service當需要和用戶交互時,由於它不能直接啟動一個Activity,因此,Service必須使用Notification來間接的啟動Activity(當用戶點擊Notification時跳轉)。
2) 自定義布局文件支持的控件類型
Notification 的自定義布局是RemoteViews,因此,它僅支持FrameLayout、LinearLayout、RelativeLayout三種布局控件, 同時支持AnalogClock、Chronometer、Button、ImageButton、ImageView、ProgressBar、 TextView、ViewFlipper、ListView、GridView、StackView和AdapterViewFlipper這些UI控 件。對於其他不支持的控件,使用時將會拋出ClassNotFoundException異常。
3) Notification支持的Intent類型(都是PendingIntent類的實例)
contentIntent:在通知窗口區域,Notification被單擊時的響應事件由該intent觸發;
deleteIntent:在通知窗口區域,當用戶點擊全部清除按鈕時,響應該清除事件的Intent;
fullScreenIntent:響應緊急狀態的全屏事件(例如來電事件),也就是說通知來的時候,跳過在通知區域點擊通知這一步,直接執行fullScreenIntent代表的事件。
上麵三種PendingIntent可以拉起Activity、Service和BroadcastReceiver,如圖所示:
4) 狀態欄通知字體的設置
不同的手機,不同的 Android平台版本,狀態欄通知窗口的背景顏色可能千差萬別,例如Android2.3之前的版本通知窗口默認背景是白色的,Android4.0之 後的版本通知窗口背景默認是黑色的,這就需要在設置Notification的字體時加以區別,否則,很容易導致通知的字體顏色和背景色一樣,從而看不到 字體部分,市麵上很多app就存在這個問題。如下圖所示,華為智匯雲和百度音樂這兩款應用就明顯存在這個問題。
從Android2.3(API level 9)開始,係統為默認通知欄布局的字體定義了樣式如下:
"android:TextAppearance.StatusBar.EventContent" "android:TextAppearance.StatusBar.EventContent.Title"
因此,在2.3之後的版本中我們自定義布局文件中的字體直接應用這個樣式就可以。對於2.3之前的版本,由於背景色是白色的,因此,我們使用如下係統預定義樣式指定字體的顏色:
?android:attr/textColorPrimary
因此,在res的values目錄下定義styles.xml文件如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="NotificationText"> <item name="android:textColor">?android:attr/textColorPrimary</item> </style> <style name="NotificationTitle"> <item name="android:textColor">?android:attr/textColorPrimary</item> <item name="android:textStyle">bold</item> </style> </resources>在res的values-v9目錄下定義styles.xml文件如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="NotificationText" parent="android:TextAppearance.StatusBar.EventContent" /> <style name="NotificationTitle" parent="android:TextAppearance.StatusBar.EventContent.Title" /> </resources>
自定義通知布局文件使用styles文件如下:
<RelativeLayout xmlns:andro xmlns:tools="https://schemas.android.com/tools" android: android:layout_width="fill_parent" android:layout_height="fill_parent" tools:ignore="ContentDescription" > <ImageView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:layout_marginLeft="5.0dp" android:layout_marginRight="10.0dp" /> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@id/image" > <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/title" /> </RelativeLayout> </RelativeLayout>
最後更新:2017-04-03 12:55:32