標籤:
原文地址:http://android.xsoftlab.net/training/run-background-service/send-request.html
上節課我們學習了如何建立IntentService。這節課我們主要學習如何通過Intent使IntentService執行工作請求。Intent可以將任何資料交給IntentService處理。你可以在Activity或者Fragment的任意方法內發送Intent給IntentService。
建立並發送工作請求到IntentService
為了建立一個工作請求並將其發送給IntentService,首先我們需要建立一個顯示的Intent對象,然後向其添加請求資料,最後再通過startService()將它發送到IntentService。
下面的代碼示範了這個過程:
-
- 為名RSSPullService的IntentService建立一個顯示的Intent。
/* * 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));
// Starts the IntentServicegetActivity().startService(mServiceIntent);
注意,你可以在Activity或者Fragment的任何地方發送工作請求。舉個例子,如果你需要先獲得使用者的輸入資料,那麼就可以將工作請求的發送代碼放在Button按鈕的點擊回調內。
一旦調用了startService(),那麼IntentService將會在onHandleIntent()方法內執行工作請求,並且它會在任務完成後自動停止。
下一個步驟就是如何將工作的完成結果反饋給請求調用處。下一節課將會學習如何使用BroadcastReceiver完成這個過程。
Android官方開發文檔Training系列課程中文版:後台服務之IntentService的使用