1.IntentService用来干什么?

一般情况下,service是在主线程中运行的,这样如果处理耗时操作会造成ANR的问题,但是很多场景下我们需要用service进行耗时操作,此时就需要一种新的机制,于是便引进了IntentService的概念。

先看一下官方的说法吧

IntentService is a base class for Services 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为了符合下面需求的场景。

  • 处理异步请求

  • 处理完请求后自动结束

2.怎么实现的上述需求?

2.1 异步处理耗时任务

先看一眼IntentService的成员:


public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
//......
}

从这里可以看出来IntentService使用handler机制实现了异步

下面进入它的生命周期


public void onCreate() {
    // TODO: It would be nice to have an option to hold a partial wakelock
    // during processing, and to have a static startService(Context, Intent)
    // method that would launch the service & hand off a wakelock.
    super.onCreate();
    HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

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

public void onDestroy() {
    mServiceLooper.quit();
}

从这里可以看出,在onCreate中使用HandlerThread的初始化了异步机制,在onstart方法中获取到Intent参数,将其放入Message中,

然后就是我上一篇博客里写过的handler使用了,这里我们来看一看此处定制的serviceHandler的实现:


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);
    }
}

在之前create方法中可以看到我们调用了构造函数,与当前线程的looper与handler相关联。

handlerMessage的方法中,我们先调用了onHandlerIntent的方法处理包含Intent的message


  protected abstract void onHandleIntent(Intent intent);

当实现IntentService时,需要重写onHandleInent方法。

2.2 自行停止功能

在执行完处理方法后,调用stopSelf方法,终止了这个Service,stopSelf的方法在其父类service中实现,使用ActivityManager进行stop操作。

因为这里的serviceHandler与当前的looper相关联,因此它工作在当前的线程中,每次只处理一个请求,如果后续请求到达该线程,则在消息队列中进行阻塞,当所有请求处理完毕后,调用stopSelf方法自行停止。由于这种规定,导致IntentService不适合同时相应多个请求,适合响应例如离线数据下载这种单一的耗时请求。


public final void stopSelf(int startId) {
    if (mActivityManager == null) {
        return;
    }
    try {
        mActivityManager.stopServiceToken(
                new ComponentName(this, mClassName), mToken, startId);
    } catch (RemoteException ex) {
    }
}

综上所述,IntentService利用Intent传递参数构建Message,然后将该Message通过Handler机制进行处理,实现了异步处理。处理后调用stopSelf进行自动停止。

这样的特性可以使我们在service中异步执行耗时操作,并且自行停止。

最后,来看个例子


public class MainActivity extends Activity {

 @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
    } 

    public void startIntentService(View source) { 
        // 创建需要启动的IntentService的Intent 
        Intent intent = new Intent(this, MyIntentService.class); 
        startService(intent); 
    } 
} 

public class MyIntentService extends IntentService { 

    public MyIntentService() { 
        super("MyIntentService"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
        // IntentService会使用单独的线程来执行该方法的代码 
        // 该方法内执行耗时任务,比如下载文件,此处只是让线程等待20秒 
        long endTime = System.currentTimeMillis() + 20 * 1000; 
        System.out.println("onStart"); 
        while (System.currentTimeMillis() < endTime) { 
            synchronized (this) { 
                try { 
                    wait(endTime - System.currentTimeMillis()); 
                } catch (InterruptedException e) { 
                    e.printStackTrace(); 
                } 
            } 
        } 
        System.out.println("----耗时任务执行完成---"); 
    } 
}
posted on 2016-05-04 17:18  岳阳楼  阅读(574)  评论(0编辑  收藏  举报