做爲剛入門Android的小白,最近在按照郭大神的《第一行代碼》在練習,在用到Notification時遇到了一些問題,網上資料比較零散,我這裏作了一個總結分析給各位,如有錯誤,懇請指正~html
Notification是一種具備全局效果的通知,程序通常經過NotificationManager服務來發送Notification。java
Notification支持文字內容顯示、震動、三色燈、鈴聲等多種提示形式,在默認狀況下,Notification僅顯示消息標題、消息內容、送達時間這3項內容。android
如下就是通知的基本佈局:app
不一樣API level的區別主要是Notification的構造方法、獲得實例的方法,這裏順便總結一下Notification的用法,按照步驟分別給出不一樣API level下的作法:佈局
一、獲取Notification管理器ui
NotificationManager noteManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
獲取管理器的方式都同樣,沒有改變。this
二、新建一個Notification,設置狀態欄顯示樣式spa
這裏只列舉了最簡單的樣式設置,具體的你們能夠參考API文檔。code
// API Level < 11 (Android 3.0) Notification notification = new Notification( R.mipmap.ic_launcher, "This is ticker text", System.currentTimeMillis());
API<11時,能夠直接用Notification的構造方法新建一個Notification,十分方便。orm
ps:我用的IDE是AndroidStudio,因此icon的id是R.mipmap.***。
// API Level >= 11 (Android 3.0) && API Level < 16 (Android 4.1) Notification.Builder builder = new Notification.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setTicker("This is ticker text") .setWhen(System.currentTimeMillis()); Notification note = builder.getNotification(); // 調用getNotification()來生成Notification
API>11後,就要用Notification.Builder()來代替了,官方API是這樣說的:
Notification(int icon, CharSequence tickerText, long when)
Notification.Builder
instead.
NotificationCompat.Builder
, available in the
Android Support library.
//API Level >= 4 (Android 1.6) && API Level < 16 (Android 4.1) NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setTicker("This is ticker text") .setWhen(System.currentTimeMillis()); Notification note =builder.getNotification(); //調用builder.getNotification()來生成Notification
所以推薦用NotificationCompat.Builder這種方式。
注意到我在註釋裏寫的 "&& API Level < 16 (Android 4.1)" 了嗎?這是由於在Google官方API文檔上是這麼說的:
public Notification getNotification () Added in API level 11
This method was deprecated in API level 16.
Use build()
instead
所以,當API>=16即Android4.1以後,就要用build()來代替了,使用方法同樣,在此就不贅述了。
三、設置Notification的觸發事件
點擊Notification後,通常都是觸發一個新的Activity:
Intent intent = new Intent(this, AnotherActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
這裏不一樣API版本都同樣。
四、設置Notification在通知欄裏的樣式
// API Level < 11 (Android 3.0) note.setLatestEventInfo(this, "This is content title", "This is content text", pi);
API<11時,調用的是Notification類的setLatestEventInfo方法。
// API Level >= 11 (Android 3.0) builder.setContentIntent(pi) .setContentTitle("This is content title") .setContentText("This is content text");
而當API>=11時,設置通知欄中的樣式是調用Builder的setContentIntent方法,設置好以後在調用build()方法生成Notification實例。
相似的,NotificationCompat.Builder也是調用一樣的方法,這裏就不贅述了。
五、發佈該Notification
第一個參數爲該notification的ID
noteManager.notify(1, note);
總結一下:
低版本(API低於十一、16)中的部分方法已經被棄用:
(1)Notification.Builder(this).getNotification()
(2)mNotification.setLatestEventInfo(this, "title", "content", null);
建議開發過程當中儘可能使用NotificationCompat.Builder(this)的構建方法去建立一個通知類。