An overview of the

IntentService maintains a thread to perform time-consuming operations, and then encapsulates the HandlerThread to create HandlerThread in the child thread.

The body of the

annotation

IntentService is a base class for {@link Service}s that handle asynchronous
requests (expressed as {@link Intent}s) on demand.  Clients send requests
through {@link android.content.Context#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.
Copy the code

IntentService IntentService is a base class that inherits from services used to handle asynchronous requests. When the client startService sends the request, the IntentService is started, and then handles the incoming Intent in a worker thread. When the task is finished, the IntentService is automatically stopped.

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 {@link #onHandleIntent(Intent)}.  IntentService
will receive the Intents, launch a worker thread, and stop the service as appropriate
Copy the code

IntentService simplifies worker processing mode, which is used to load time-consuming tasks for the main application thread, and focuses on time-consuming tasks. To use IntentService, you inherit from IntentService and override the onHandleIntent method. An IntentService receives a set of intEnts, starts a child thread, and then actually closes 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.
Copy the code

All requests are processed in the same child thread — they can take a long time (without blocking the application loop thread), but IntentService can only handle one request at a time.

IntentService: IntentService: IntentService: IntentService: IntentService: IntentService: IntentService: IntentService: IntentService: IntentService: IntentService However, it can only handle one task at a time, so it is not suitable for high concurrency and is suitable for the situation with a small number of requests, similar to APP version detection update, background positioning function and reading a small number of IO operations.

Member variables

    private volatile Looper mServiceLooper;// Looper in the child thread
    private volatile ServiceHandler mServiceHandler;// A Handler is held internally
    private String mName;// The name of the thread created internally
    private boolean mRedelivery;// Whether to call onStartCommand to return an Intent after the service is terminated
Copy the code

ServiceHandler

  private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
          // The child thread calls back the IntentonHandleIntent((Intent)msg.obj); stopSelf(msg.arg1); }}Copy the code

Internally we create a ServiceHandler that wraps the incoming Intent as a Message, and then wraps the Message as an Intent, calling onHandleIntent, The purpose of the conversion is to switch the Intent from the main thread to the child thread.

A constructor

Public IntentService(String name) {super(); mName = name; }Copy the code

onCreate

    @Override
    public void onCreate(a) {
        super.onCreate();
        / / create a HandlerThread
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        // Start thread to create child thread Looper
        thread.start();
        // Get the child thread Looper
        mServiceLooper = thread.getLooper();
       // Create child thread Handler
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }
Copy the code

onStartCommand

  @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        // Call onStart
        onStart(intent, startId);
       // Determine whether a sticky or non-sticky broadcast is returned to retransmit the Intent based on the value of mRedelivery
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }
Copy the code

onStart

  @Override
    public void onStart(@Nullable Intent intent, int startId) {
        // Create a Message
        Message msg = mServiceHandler.obtainMessage();
      	// Message flag, as the current Service flag
        msg.arg1 = startId;
      	/ / with Intent
        msg.obj = intent;
      	// The message is sent, at which point the thread is switched to the child thread
        mServiceHandler.sendMessage(msg);
    }


   @Override
        public void handleMessage(Message msg) {
            // Process incoming messages in the child thread
            onHandleIntent((Intent)msg.obj);
           // Stop the Service after the message is processed
            stopSelf(msg.arg1);
        }
Copy the code

onDestroy

    @Override
    public void onDestroy(a) {
       / / out of stars
        mServiceLooper.quit();
    }
Copy the code

use

IntentService intentService = new IntentService("main") {
    @Override
    protected void onHandleIntent(Intent intent) {
        // Process time-consuming operations}};// Do not worry about the Service lifecycle, IntentService will take care of itself
Copy the code

conclusion

IntentService actually instantiates a HandlerThread internally and encapsulates a Handler, so its workflow is as follows: IntentService instantiates a HandlerThread internally and encapsulates a Handler.

  1. Create a HandlerThread and enable the HandlerThread to create a Looper
  2. Create a Handler, pass in Looper, and instantiate the Handler in the child thread
  3. The Intent picked up in onStartCommand is sent as the obj of the message
  4. The message is then processed in the onHandleIntent, in the child thread
  5. Like HandlerThread,IntentService is implemented internally by a Handler, so tasks are executed serially and are not suitable for time-consuming operations.