Service和IntentService的区别

2018-07-12  本文已影响0人  GexYY

Service相信大家都比较熟悉了,就不重点做阐述解释了.

IntentService也是继承Service,但是和正常的Service的区别有2点:

分析IntentService源码:

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

发现再onCreate()中开启来一个HandlerThread,并创建来ServiceHandler,从而保证当前任务的异步处理和任务的单一处理;


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

我们看到再onStart()方法中,mServiceHandler发送来执行任务的msg,接下来我们看下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);
        }
    }

可以看到接收到任务后,直接调用onHandlerIntent()方法来处理异步任务,任务结束后自动调用stopSelf()来终止线程
经常我们的在广播或者Service的接收中要处理相关的耗时操作,建议采用IntentService来优化处理
到此,通过分析源码,之前说的2个区别都可以很明白的解释了!

上一篇下一篇

猜你喜欢

热点阅读