天天看點

PendingIntent詳解

PendingIntent描述了一個Intent和目标action。這個類的執行個體是用getActivity(Context,int,Intent,int)方法和getBroadcast(Context,int,Intent,int)和getService(Context,int,Intent,int)方法建立的。建立出的pending intent可以交給其它程式,于是它們可以在以後的某個時間以你的名義執行intent中所描述的動作。

通過給于一個PendingIntent,你可以使其它程式像你自己一樣執行你所指定的操作(具有相同的權限和身份)。是以,你需要小心的建立PendingIntent:通常,你最基本的應該明确設定你的相關元件的名字,以保證将來intent是被發送給它而不是其它地方。

一個PendingIntent本是隻是簡單地引用一個由系統維護的一個令牌,這個令牌描述了用于取得PendingIntent的原始資料。這表示即使擁有這個PendingIntent的程序關閉了,但這個PendingIntent對于那些收到它的程序依然有效。如果建立這個PendingIntent的程式又重新運作并重新擷取同一個類型的PendingIntent(相同的操作,action,資料,類型群組件以及相同的标志),那麼擷取的還是這個PendingIntent,并且這個程式可以用cancel()來删除這個PendingIntent。

Intent和PendingIntent的差別?

intent英文意思是意圖,pending表示即将發生或來臨的事情。 

PendingIntent這個類用于處理即将發生的事情。比如在通知Notification中用于跳轉頁面,但不是馬上跳轉。 

Intent 是及時啟動,intent 随所在的activity 消失而消失。 

PendingIntent 可以看作是對intent的包裝,通常通過getActivity,getBroadcast ,getService來得到pendingintent的執行個體,目前activity并不能馬上啟動它所包含的intent,而是在外部執行 pendingintent時,調用intent的。正由于pendingintent中 儲存有目前App的Context,使它賦予外部App一種能力,使得外部App可以如同目前App一樣的執行pendingintent裡的 Intent, 就算在執行時目前App已經不存在了,也能通過存在pendingintent裡的Context照樣執行Intent。另外還可以處理intent執行後的操作。常和alermanger 和notificationmanager一起使用。 

Intent一般是用作Activity、Sercvice、BroadcastReceiver之間傳遞資料,而Pendingintent,一般用在 Notification上,可以了解為延遲執行的intent,PendingIntent是對Intent一個包裝。 

PendingIntent就是一個Intent的描述,我們可以把這個描述交給别的程式,别的程式根據這個描述在後面的别的時間做你安排做的事情 (By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself,就相當于PendingIntent代表了Intent)。

繼續閱讀