天天看點

android: Android Notification

notification即通知,用于在通知欄顯示提示資訊。

在較新的版本中(api level  > 11),notification類中的一些方法被android聲明deprecated(棄用),其實基本上相當于全部棄用了,因為這個類本身方法就少得可憐。

android官方聲明棄用,一定有它的理由,雖然我也不知道是什麼。奈何本人輕度強迫症患者,人家都建議你不要用了,那就不要老是恪守着n年前的東西了。

就像是以前,一說到标簽頁,大家基本上都會想到tabhost配合activitygroup,但android後來提倡fragment。

廢話說多了,還是小結一下使用方法。下面按照建立一個通知的步驟一步一步來,同時給出新舊實作方法。

1、擷取notification管理器

notificationmanager notemng = (notificationmanager)getsystemservice(notification_service);

2、建立一個notification,設定狀态欄顯示樣式

private notification note;

//api 11以下

note = new notification(r.drawable.ico_launcher "顯示于螢幕頂端狀态欄的文本", system.currenttimemillis());

//api 11及以上

notification.builder builder = new notification.builder(nowcontext).setticker("顯示于螢幕頂端狀态欄的文本")

.setsmallicon(r.drawable.ic_laucher);

api 11以上版本中,狀态欄顯示的樣式跟下拉通知欄中顯示的樣式,可以一起設定,就是通過notification.builder類來實作,這裡的builder隻調用了兩個方法來設定狀态欄顯示樣式。

3、設定notification标志位(非必要步驟)

//flag_ongoing_event表明有程式在運作,該notification不可由使用者清除

note.flags = notification.flag_ongoing_event;

4、設定點選notification後的觸發事件

//通過intent,使得點選notification之後會啟動新的activity

intent i = new intent(nowcontext, anotheractivity.class);

//該标志位表示如果intent要啟動的activity在棧頂,則無須建立新的執行個體

i.setflags(intent.flag_activity_single_top);

pendingintent = pendingintent.getactivity(nowcontext, 100, i, pendingintent.flag_update_current);

5、設定notification在通知欄裡的樣式

(1)系統預設樣式

//api 11以下:

note.setlatesteventinfo(nowcontext, "take me to your heart", "micheal learn to rock", pendingintent);

//api 16及以上,build()方法要求api 16及以上

//一會api 11以上,一會api16以上,我也很想知道android的api是怎麼設計的

note = builder.setcontentintent(pendingintent).setcontenttitle("title").setcontenttext("text").build();

(2)自定義樣式:

自定義樣式,就是讓notification在通知欄顯示成自定義的xml布局

應當注意的是,notification的自定義樣式,隻支援以下可視元件:

framelayout, linearlayout, relativelayout

textview, button, analogclock, imageview, imagebutton, chronometer, progressbar

remoteview view = new remoteview(nowactivity.getpackagename(), r.layout.note_layout);

note.contentview = view;

note.contentintent = pendingintent;

//api 16及以上,又是build()方法導緻的,汗。。

note = builder.setcontent(view).setcontentintent(pendingintent).build();

這個步驟裡有一個很值得注意的地方:pendingintent被設定為note的contentintent的值,就意味着點選了這個通知才會觸發該intent。

那麼如果隻是想讓自定義布局裡的某個按鈕觸發呢?比如說,弄了一個音樂播放器,service負責播放音樂,notification顯示目前播放進度和一些簡單的暫停按鈕、上一首、下一首按鈕,讓使用者不用再打開界面就可以通過notification上的按鈕操縱音樂播放。

假設說想讓自定義布局裡的一個id為r.id.button1的按鈕來觸發這個intent,可以如下操作:

view.setonclickpendingintent(r.id.button1, pendingintent);//在上面建立remoteview執行個體後加上這句

然後注意,pendingintent已經綁定到按鈕上了,上面notificatiion執行個體中,設定contentintent的語句要去掉。

6、釋出該通知,第一個參數為該notification的id

notemng.notify(10, note);

ps:這個是我自己敲的一個txt檔案,在我電腦裡,可能一些變量名什麼的會敲錯。

但是大概步驟跟方法相信已經說清楚了。