Android中使用IntentService建立後台服務執行個體_Android

來源:互聯網
上載者:User

IntentService提供了在單個後台線程運行操作的簡單結構。這允許它操作耗時操作,而不影響UI響應。同樣,IntentService也不影響UI生命週期事件,所以,它在某些可能關閉AsyncTask的情況下,仍會繼續運行(實測在Activity的onDestory裡寫AsyncTask無法運行)。

IntentService有如下限制:

1.它不能直接影響UI。要把結果反映給UI,需要發給Activity
2.工作請求會順序運行。如果一個操作未結束,後面發送的操作必須等它結束(單線程)
3.IntentService裡啟動並執行操作無法被中斷

然而,在大多數情況下,IntentService是簡單背景工作的首選方式。

本節展示了如何建立IntentService的子類,如何建立onHandleIntent()回調,如何在AndroidManifest.xml聲明IntentService。

建立IntentService

定義一個IntentService的子類,覆蓋onHandleIntent()方法:

複製代碼 代碼如下:

public class RSSPullService extends IntentService {
    @Override
    protected void onHandleIntent(Intent workIntent) {
        // Gets data from the incoming Intent
        String dataString = workIntent.getDataString();
        ...
        // Do work here, based on the contents of dataString
        ...
    }
}

提示:其他Service正常的回調,像 onStartCommand()在IntentService裡會自動調用。在IntentService裡,應該避免覆蓋這些回調。

在AndroidManifest.xml裡定義IntentService

IntentService也是Service),需要在AndroidManifest.xml裡註冊。

複製代碼 代碼如下:

<application
        android:icon="@drawable/icon"
        android:label="@string/app_name">
        ...
        <!--
            Because android:exported is set to "false",
            the service is only available to this app.
        -->
        <service
            android:name=".RSSPullService"
            android:exported="false"/>
        ...
    <application/>

android:name屬性指定了IntentService的類名。

注意:&ltservice>節點不能包含intent filter。發送工作請求的Activity使用明確的Intent,會指定哪個IntentService。這也意味著,只有同一個app裡的組件,或者另一個有相同user id的應用才能訪問IntentService。

現在你有了基礎的IntentService類,可以用Intent對象發送工作請求。

建立發送工作請求傳給IntentService

建立一個明確的Intent,添加需要的資料,調用startService()發送給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));
//Call startService()
// Starts the IntentService
getActivity().startService(mServiceIntent);

提示:可以在Activity or Fragment的任意位置發送工作請求。如果你需要先取到使用者輸入,你可以在點擊事件或類似手勢的回調方法裡發送工作請求。

一旦調用了startService(),IntentService會在onHandleIntent()工作,完了結束自身。

下一步是報告結果給原來的Activity或Fragment,下節講如何用BroadcastReceiver實現。請參考此文:http://www.jb51.net/article/51548.htm

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.