W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
編寫: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)建一個(gè)任務(wù)請求并發(fā)送到IntentService。需要先創(chuàng)建一個(gè)顯式Intent,并將請求數(shù)據(jù)添加到intent中,然后通過調(diào)用 startService()
方法把任務(wù)請求數(shù)據(jù)發(fā)送到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));
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ù)。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: