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

2018-08-02 18:23 更新

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

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

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

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

下面的是代碼示例:

  • 創(chuàng)建一個新的顯式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ā)送任務請求。例如,如果你先獲取用戶輸入,您可以從響應按鈕單擊或類似手勢的回調方法里面發(fā)送任務請求。

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

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


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號