Android IntentService use and source code analysis

IntentService is a special Service, which inherited the Service and is an abstract class, so you must create a subclass to use IntentService. IntentService generally used to perform time-consuming background tasks, when the task is completed automatically stops execution; and because it is a service, much higher than the priority of the thread, less likely to be killed by the system, and therefore more suitable for the implementation of a number of high priority background tasks.

A, IntentService use

IntentService relatively simple to use, the following steps will be described by using a IntentService example.

1. Create a subclass IntentService rewriting onHandleIntent method, time-consuming tasks in onHandleIntent

public class ChildIntentService extends IntentService {

    public ChildIntentService() {
        super("aaa");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //执行耗时任务
        Log.d(TAG, "onHandleIntent: start");
        String serviceName = intent.getStringExtra("serviceName");
        if (TextUtils.equals(serviceName, "a")){
            simulationTask();
            Log.d(TAG, "onHandleIntent: simulationTask complete");
        }
    }

    /**
     * 模拟耗时任务
     */
    private void simulationTask() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Destroy ChildIntentService");
    }
}

2. Start IntentService

public void start(View view) {
    Intent intent = new Intent(MainActivity.this, ChildIntentService.class);
    intent.putExtra("serviceName", "a");
    startService(intent);
}

3. Print log information

2019-05-31 18:05:41.712 11300-11349/architecture.android.com.architecture D/qianwei: onHandleIntent: start
2019-05-31 18:05:46.713 11300-11349/architecture.android.com.architecture D/qianwei: onHandleIntent: simulationTask complete
2019-05-31 18:05:46.716 11300-11300/architecture.android.com.architecture D/qianwei: Destroy ChildIntentService

We see, IntentService indeed will automatically stop when the end of the mandate.

Two, IntentService source code analysis

On realization, IntentService encapsulates HandlerThread and Handler, when IntentService is first started, it will call its onCreate method, we first look at its onCreate ways:

@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 method creates a thread HandlerThread objects and call its start method, the use of this HandlerThread Looper create ServiceHandler objects mServiceHandler, this message will eventually be sent by mServiceHandler performed HandlerThread in.

Each time you start IntentService, it onStartCommand method will be called once, we first look at onStartCommand method:

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

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
    onStart(intent, startId);
    return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}

We can see, onStartCommand method call onStart direct method: onStart method just intent encapsulated into a message and sent via mServiceHandler. We continue to look at internal ServiceHandler implementation:

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

Internal ServiceHandler very simple, it will message to onHandleIntent method for processing after receiving the message, the method requires us to implement onHandleIntent subclasses, its role is distinguished by Intent specific tasks and execute them. After the end of the onHandleIntent method calls IntentService of stopSelf (int startId) method to try to stop the service, because this time there may be other unprocessed messages, all messages are processed only will really stop the service.

Now that we know, is inside IntentService request HandlerThread perform tasks by way of the message, but also a HandlerThread internal use Handler of Thread, which means IntentService and Looper is executed as a background task order.


reference

"Android development of artistic exploration."

Reproduced in: https: //www.jianshu.com/p/2d5dbb7fe202

Guess you like

Origin blog.csdn.net/weixin_34270865/article/details/91136131