Android官方開發文檔Training系列課程中文版:後台服務之IntentService的使用

來源:互聯網
上載者:User

標籤:

原文地址: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。

下面的代碼示範了這個過程:

    1. 為名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));
    1. 調用startService()。
// Starts the IntentServicegetActivity().startService(mServiceIntent);

注意,你可以在Activity或者Fragment的任何地方發送工作請求。舉個例子,如果你需要先獲得使用者的輸入資料,那麼就可以將工作請求的發送代碼放在Button按鈕的點擊回調內。

一旦調用了startService(),那麼IntentService將會在onHandleIntent()方法內執行工作請求,並且它會在任務完成後自動停止。

下一個步驟就是如何將工作的完成結果反饋給請求調用處。下一節課將會學習如何使用BroadcastReceiver完成這個過程。

Android官方開發文檔Training系列課程中文版:後台服務之IntentService的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.