Android 向后臺服務(wù)發(fā)送任務(wù)請求

2018-08-02 18:23 更新

編寫:kesenhoo - 原文:http://developer.android.com/training/run-background-service/send-request.html

前一篇文章演示了如何創(chuàng)建一個(gè)IntentService類。這次會演示如何通過發(fā)送一個(gè)Intent來觸發(fā)IntentService執(zhí)行任務(wù)。這個(gè)Intent可以傳遞一些數(shù)據(jù)給IntentService。我們可以在Activity或者Fragment的任何時(shí)間點(diǎn)發(fā)送這個(gè)Intent。

創(chuàng)建任務(wù)請求并發(fā)送到IntentService

為了創(chuàng)建一個(gè)任務(wù)請求并發(fā)送到IntentService。需要先創(chuàng)建一個(gè)顯式Intent,并將請求數(shù)據(jù)添加到intent中,然后通過調(diào)用 startService() 方法把任務(wù)請求數(shù)據(jù)發(fā)送到IntentService。

下面的是代碼示例:

  • 創(chuàng)建一個(gè)新的顯式Intent用來啟動IntentService。
/*
 * Creates a new Intent to start the RSSPullService
 * IntentService. Passes a URI in the
 * Intent's "data" field.
 */
mServiceIntent = new Intent(getActivity(), RSSPullService.class);
mServiceIntent.setData(Uri.parse(dataUrl));
  • 執(zhí)行startService()
// Starts the IntentService
getActivity().startService(mServiceIntent);

注意可以在Activity或者Fragment的任何位置發(fā)送任務(wù)請求。例如,如果你先獲取用戶輸入,您可以從響應(yīng)按鈕單擊或類似手勢的回調(diào)方法里面發(fā)送任務(wù)請求。

一旦執(zhí)行了startService(),IntentService在自己本身的onHandleIntent()方法里面開始執(zhí)行這個(gè)任務(wù),任務(wù)結(jié)束之后,會自動停止這個(gè)Service。

下一步是如何把工作任務(wù)的執(zhí)行結(jié)果返回給發(fā)送任務(wù)的Activity或者Fragment。下節(jié)課會演示如何使用BroadcastReceiver來完成這個(gè)任務(wù)。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號