IntentService与普通Service的区别

1.onCreate

在IntentService的onCreate方法里:

  • 创建HandlerThread
  • 创建ServiceHandler,所以发送消息给ServiceHandler的话,事件将会在HandlerThread上处理。
public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    
    @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);
    }
}
    

2.onStartCommand

onStartCommand里面调用onStart方法

public abstract class IntentService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }
}
    

3.onStart

发送消息给mServiceHandler

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

4.handleMessage

handleMessage方法里面调用onHandlerIntent

public abstract class IntentService extends Service {
    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);
        }
    }
}    
    

5.onHandleIntent

onHandleIntent由子类覆盖实现

public abstract class IntentService extends Service {
    protected abstract void onHandleIntent(Intent intent);
}

总结

使用IntentService的时候,需要覆盖onHandleIntent方法,startService后,最终会触发onHandleIntent方法,这个方法在HandlerThread执行,是在线程上,所以可以做耗时的操作。

你可能感兴趣的:(Android,Android,IntentService)