Android IntentService使用


概述

演示使用Android 中IntentService的方法。IntentService一般情況下,用於后台處理一些耗資源的任務。本例子有演示使用這個IntentService類的代碼,並可運行。

詳細

原文地址:http://blog.csdn.net/VNanyesheshou/article/details/75125909

一、准備工作

 

開發環境:

jdk1.8

Eclipse Luna Service Release 1 (4.4.1)

運行環境:

華為榮耀6(Android4.4)、華為p9(Android7.0)

實現功能:

Android IntentService的使用

二、簡介

IntentService概括

IntentService is a base class for Service that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(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. 
This “work queue processor” pattern is commonly used to offload tasks from an application’s main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate. 
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.

IntentService是Service的子類,根據需要處理異步請求(以intent表示)。客戶端通過調用startService(Intent) 發送請求,該Service根據需要啟動,使用工作線程處理依次每個Intent,並在停止工作時停止自身。 
這種“工作隊列處理器”模式通常用於從應用程序的主線程中卸載任務。 IntentService類的存在是為了簡化這種模式。 要使用它,擴展IntentService並實現onHandleIntent(Intent)。 IntentService將收到Intents,啟動一個工作線程,並根據需要停止該服務。 
所有請求都在單個工作線程處理 - 它們可能需要很長的時間(並且不會阻止應用程序的主循環),但是一次只會處理一個請求

三、程序實現

工程截圖:

8BY31Y]N_5H4{15)JFVYJY9.png

在IntentService中處理下載請求(模擬),並將進度更新到Ui。 
MyIntentService.Java代碼如下:

public class MyIntentService extends IntentService {
    private final static String TAG = "MyIntentService";
    
    public static final String ACTION_DOWN_IMG = "down.image";
    public static final String ACTION_DOWN_VID = "down.vid";

    public static final String ACTION_DOWN_PROGRESS = "com.zpengyong.down.progress";
    public static final String ACTION_SERVICE_STATE = "com.zpengyong.service.state";
    
    public static final String PROGRESS = "progress";
    public static final String SERVICE_STATE = "service_state";

    //構造方法
    public MyIntentService() {
        super("MyIntentService");
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        sendServiceState("onCreate");
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "");
    }
    
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(TAG, "onHandleIntent thread:"+Thread.currentThread());
        String action = intent.getAction();
        if(action.equals(ACTION_DOWN_IMG)){
            for(int i = 0; i < 100; i++){
                try{ //模擬耗時操作
                    Thread.sleep(50);
                }catch (Exception e) {
                }
                sendProgress(i);
            }
        }else if(action.equals(ACTION_DOWN_VID)){
            for(int i = 0; i < 100; i++){
                try{ //模擬耗時操作
                    Thread.sleep(70);
                }catch (Exception e) {
                }
                sendProgress(i);
            }
        }
        Log.i(TAG, "onHandleIntent end");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        sendServiceState("onDestroy");
    }
    //發送Service的狀態
    private void sendServiceState(String state){
        Intent intent = new Intent();
        intent.setAction(ACTION_SERVICE_STATE);
        intent.putExtra(SERVICE_STATE, state);
        sendBroadcast(intent);
    }
    
    //發送進度
    private void sendProgress(int progress){
        Intent intent = new Intent();
        intent.setAction(ACTION_DOWN_PROGRESS);
        intent.putExtra(PROGRESS, progress);
        sendBroadcast(intent);
    }
}

使用IntentService的方法:

  1. 繼承IntentService。

  2. 實現不帶參數的構造方法,並且調用父類IntentService的構造方法。

  3. 實現onHandleIntent方法。

在onHandleIntent方法中可以根據intent來區分任務,這里有兩個任務,一個是下載圖片、一個是下載視頻(模擬耗時操作)。

四、運行效果

項目下載后,導入eclipse后,右鍵項目:Run as -》Android Application

然后有以下效果:

1 只點擊“啟動任務一”。 
這里寫圖片描述 
打印:

07-15 03:07:24.589: I/MyIntentService(3186): onCreate
07-15 03:07:24.593: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:07:30.918: I/MyIntentService(3186): onHandleIntent end
07-15 03:07:31.017: I/MyIntentService(3186): onDestroy

IntentService啟動后再onHandleIntent方法中執行任務(該方法工作在子線程中),任務執行完后,IntentService銷毀。

2 點擊“啟動任務一”,任務未完成時點擊“停止Service”。 
這里寫圖片描述 
log

07-15 03:08:08.477: I/MyIntentService(3186): onCreate
07-15 03:08:08.478: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:08:12.203: I/MyIntentService(3186): onDestroy
07-15 03:08:14.253: I/MyIntentService(3186): onHandleIntent end

IntentService中線程執行任務時,stopService會讓IntentService銷毀,但是任務繼續執行,直到執行完成線程退出。

3 點擊“啟動任務一”,任務完成后點擊“啟動任務二”。 
這里寫圖片描述 
log信息:

07-15 03:11:42.366: I/MyIntentService(3186): onCreate
07-15 03:11:42.367: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:11:48.285: I/MyIntentService(3186): onHandleIntent end
07-15 03:11:48.289: I/MyIntentService(3186): onDestroy
07-15 03:11:50.174: I/MyIntentService(3186): onCreate
07-15 03:11:50.205: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:11:58.446: I/MyIntentService(3186): onHandleIntent end
07-15 03:11:58.510: I/MyIntentService(3186): onDestroy

由上可知,任務執行完成后,線程退出循環,Service銷毀。重新開啟任務則重新創建Service,執行任務。

4 點擊“啟動任務一”,任務完成前點擊“啟動任務二”。 
這里寫圖片描述 
log信息

07-15 03:16:46.998: I/MyIntentService(3186): onCreate
07-15 03:16:46.998: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:16:52.980: I/MyIntentService(3186): onHandleIntent end
07-15 03:16:52.980: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:17:01.048: I/MyIntentService(3186): onHandleIntent end
07-15 03:17:01.053: I/MyIntentService(3186): onDestroy

正常startService啟動兩個任務,第一個未完成前,將第二個任務放到隊列中,等待第一個完成后執行第二個任務,第二個任務完成后,Service自動銷毀。

5 點擊“啟動任務一”,任務完成前點擊“停止Service”,然后再點擊“啟動任務二”。 
這里寫圖片描述 
log信息 
這里寫圖片描述 
第一個任務尚未結束時stopservice,IntentService銷毀,其線程繼續運行(tid 3691)。此時重新startService會開啟IntentService,其會重新創建一個線程運行任務(tid 3692)。兩個任務在兩個線程中運行,所以其執行完的先后順序不確定。

五、補充說明:IntentService源碼解析

路徑:frameworks/base/core/java/android/app/IntentService.java 
先看下IntentService的構造方法和onCreate()。

public abstract class IntentService extends Service {
    //Creates an IntentService.Invoked by your subclass's constructor.
    public IntentService(String name) {
            super();
        mName = name;
    }
     @Override
    public void onCreate() {
             super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }
    。。。。
}

IntentService 是繼承Service的一個抽象類,所以需要繼承IntentService 並必須實現其抽象方法onHandleIntent。 
繼承IntentService需要實現一個空的構造器,並且調用IntentService的構造器。 
在onCreate()方法中創建了一個HandlerThread,並允許該線程。HandlerThread 不太懂的可以參考我的上一篇文章Android HandlerThread詳解 。 
獲取子線程中的Looper實例,然后創建與子線程綁定的Handler對象。

 

接着看IntentService的onStart()。

public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
     msg.arg1 = startId;
     msg.obj = intent;
     mServiceHandler.sendMessage(msg);
}

在onStart方法中,創建Message對象,並將“消息”通過mServiceHandler發送到子線程中的消息隊列中。 
我們知道這些消息處理還是會分發到Handler中。接着看mServiceHandler

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
             super(looper);
     }
     @Override
     public void handleMessage(Message msg) {
             onHandleIntent((Intent)msg.obj);
         stopSelf(msg.arg1);
    }
}

消息會在handlerMessage中處理,該方法中調用了onHandleIntent,所以我們需要實現onHandleIntent,在該方法中做我們要做的任務。而消息處理完成后,調用stopSelf將自身Service銷毀。這里可能會有疑問,既然一個任務執行完成后就會執行stopSelf,那多個任務是怎么處理的呢?這里stopSelf(msg.arg1),會先看隊列中是否有消息待處理,如果有則繼續處理后面的消息,沒有才會將Service銷毀。 

接着看IntentService的onDestroy方法。

@Overridepublic void onDestroy() {
    mServiceLooper.quit();
}

在IntentService的onDestroy方法中會調用looper的quit方法,將子線程的消息循環停止,等待任務完成后結束子線程。

 

六、總結

IntentService是一個比較便捷的類,省了我們在創建Thread,但是並不能適合所有的情況,它會創建一個線程,多個任務按順序執行,並且執行過程中不能夠取消該任務。所以還是需要根據情況進行使用。

 

注:本文著作權歸作者,由demo大師發表,拒絕轉載,轉載需要作者授權


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM