1. 程式人生 > >android 中IntentService的使用場景

android 中IntentService的使用場景

rtl 其中 簡單 color content ont long ack hand

IntentService是繼承並處理異步請求的一個類,在IntentService內有一個工作線程來處理耗時操作,啟動IntentService的方式和啟動傳統的Service一樣,同時,當任務執行完後,IntentService會自動停止,而不需要我們手動去控制或stopSelf()。另外,可以啟動IntentService多次,而每一個耗時操作會以工作隊列的方式在IntentService的onHandleIntent回調方法中執行,並且,每次只會執行一個工作線程,執行完第一個再執行第二個,以此類推。

在Android開發中,我們或許會碰到這麽一種業務需求,一項任務分成幾個子任務,子任務按順序先後執行,子任務全部執行完後,這項任務才算成功。那麽,利用幾個子線程順序執行是可以達到這個目的的,但是每個線程必須去手動控制,而且得在一個子線程執行完後,再開啟另一個子線程。或者,全部放到一個線程中讓其順序執行。這樣都可以做到,但是,如果這是一個後臺任務,就得放到Service裏面,由於Service和Activity是同級的,所以,要執行耗時任務,就得在Service裏面開子線程來執行。那麽,有沒有一種簡單的方法來處理這個過程呢,答案就是IntentService。

什麽是IntentService,首先看看官方的解釋:
IntentService is a base class forServices that handle asynchronous requests (expressed asIntents) on demand. Clients send requests throughstartService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work


簡單說,IntentService是繼承於Service並處理異步請求的一個類,在IntentService內有一個工作線程來處理耗時操作,啟動IntentService的方式和啟動傳統Service一樣,同時,當任務執行完後,IntentService會自動停止,而不需要我們去手動控制。另外,可以啟動IntentService多次,而每一個耗時操作會以工作隊列的方式在IntentService的onHandleIntent回調方法中執行,並且,每次只會執行一個工作線程,執行完第一個再執行第二個,以此類推。
還有一個說明是:
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application‘s main loop), but only one request will be processed at a time.
大致意思是:所有請求都在一個單線程中,不會阻塞應用程序的主線程(UI Thread),同一時間只處理一個請求。
那麽,用IntentService有什麽好處呢?首先,我們省去了在Service中手動開線程的麻煩,第二,當操作完成時,我們不用手動停止Service,第三,it‘s so easy to use!

package im.weiyuan.com.viewutils;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.SystemClock;
import android.util.Log;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class MyIntentService extends IntentService {


    /**
     * 必須要寫一個無參數的構造函數,然後調用父類的 super("MyIntentService");
     * 其中MyIntentService就是執行onHandleIntent對應的線程的名字
     * */
    public MyIntentService() {
        super("MyIntentService");
    }




    /**
     * onHandleIntent函數是在子線程中去執行處理的,所以這裏就沒有必要去開啟線程
     * */

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("123456","onHandleIntent is called");
        /**
         * 模擬耗時操作
         * */
        SystemClock.sleep(10000);
        Log.d("123456","onHandleIntent is out");
    }

    /**
     * onHandleIntent函數中的耗時任務執行完成後,服務會自動銷毀
     * 調用onDestroy函數
     *
     * */

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("123456","onDestroy is called");
    }
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="im.weiyuan.com.viewutils">

    <permission android:name="com.weiyuan.sb" />

    <uses-permission android:name="com.weiyuan.sb" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyIntentService"
            android:exported="false"></service>
    </application>

</manifest>
Intent intent = new Intent(MainActivity.this,MyIntentService.class);
startService(intent);
我們來看看日誌打印的輸出:

07-23 11:52:18.507 14993-15238/im.weiyuan.com.viewutils D/123456: onHandleIntent is called
07-23 11:52:28.508 14993-15238/im.weiyuan.com.viewutils D/123456: onHandleIntent is out
07-23 11:52:28.510 14993-14993/im.weiyuan.com.viewutils D/123456: onDestroy is called

不清楚的看博客:

http://blog.csdn.net/ryantang03/article/details/8146154/

相當的經典

android 中IntentService的使用場景