天天看點

怎樣使用PendingIntent讓Service和Client進行互動

熟悉Android的朋友都知道使用bindService()啟動Service可以通過IBinder對象實作Service和Client端通信,本篇文章并不是介紹啟動Service的常見方法(startService()和bindService()),如果想知道Service的基本運用,請繞道……

本篇文章主要講述一種并不是很常見的啟動Service的方式,并與Service端進行互動的實作方式,準備好了嗎?現在開始我們的探索之旅!

 俗話說,衆裡尋他千百度,蓦然回首那人卻在燈火闌珊處。運用到學習知識上面也同樣如此,為了探索PendingIntent啟動Service的實作方式,搜尋了很多資料都沒有找到滿意的結果。最終還是決定再撸一篇Android文檔,終于皇天不負有心人,在文檔中找到了相關的說明(Website:Android說明文檔),是以建議大家多看Android說明文檔,學會學習第一手知識的方法,也就是所說的多穿一手鞋。

以下是從文檔中摘錄的一段話(隻要講述了可以使用PendingIntent+Broadcast的方式實作Client和Service的互動):

If the service does not also provide binding, the intent delivered with

startService()

is the only mode of communication between the application component and the service. However, if you want the service to send a result back, then the client that starts the service can create a

PendingIntent

for a broadcast (with

getBroadcast()

) and deliver it to the service in the

Intent

that starts the service. The service can then use the broadcast to deliver a result.

 以上講了那麼多,現在來看看具體的實作方式吧!

 未完待續,敬請期待!