PendingIntent作用

其實和Intent作用差不多,可以理解爲是一種特殊的Intent。和Intent區別在於執行的時機不一樣。Intent是立刻執行,PendingIntent是等待條件滿足在執行。常用於通知、短信、鬧鐘等應用情景。

PendingIntent Flag介紹
FLAG_ONE_SHOT:獲取的PendingIntent只能使用一次。

FLAG_NO_CREATE:利用FLAG_NO_CREAT獲取的PendingIntent,若描述的Intent不存在則返回NULL值

FLAG_CANCEL_CURRENT:如果描述的PendingIntent已經存在,則在產生新的Intent之前會先取消掉當前的。

FLAG_UPDATE_CURRENT:能夠新new一個 Intent

2 獲取PendingIntent
關於PendingIntent的實例獲取一般有以下五種方法,分別對應Activity、Broadcast、Service

getActivity()
getActivities()
getBroadcast()
getService()
getForegroundService()
它們的參數都相同,都是四個:Context, requestCode, Intent, flags,分別對應上下文對象、請求碼、請求意圖用以指明啓動類及數據傳遞、關鍵標誌位。
前面三個參數共同標誌一個行爲的唯一性,而第四個參數flags:

FLAG_CANCEL_CURRENT:如果當前系統中已經存在一個相同的PendingIntent對象,那麼就將先將已有的PendingIntent取消,然後重新生成一個PendingIntent對象。
FLAG_NO_CREATE:如果當前系統中不存在相同的PendingIntent對象,系統將不會創建該PendingIntent對象而是直接返回null,如果之前設置過,這次就能獲取到。
FLAG_ONE_SHOT:該PendingIntent只作用一次。在該PendingIntent對象通過send()方法觸發過後,PendingIntent將自動調用cancel()進行銷燬,那麼如果你再調用send()方法的話,系統將會返回一個SendIntentException。
FLAG_UPDATE_CURRENT:如果系統中有一個和你描述的PendingIntent對等的PendingInent,那麼系統將使用該PendingIntent對象,但是會使用新的Intent來更新之前PendingIntent中的Intent對象數據,例如更新Intent中的Extras
備註:兩個PendingIntent對等是指它們的operation一樣, 且其它們的Intent的action, data, categories, components和flags都一樣。但是它們的Intent的Extra可以不一樣

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章