Android development-IntentService usage, what do you miss, androidservice usage

Source: Internet
Author: User

Android development-IntentService usage, what do you miss, androidservice usage

IntentService is a background service class provided by Android. We send request commands to IntentService through Intent in external components. Then, IntentService executes the commands in the command queue one by one and receives the first command, intentService starts and starts a background thread to execute the First Command. Then, the commands in the queue are executed sequentially. After all the commands in the queue are executed, the service is stopped and destroyed immediately.

Usage of different intentservices than services

1. write your own Service class to inherit the IntentService, and override the onHandleIntent (Intent) method. This method is an abstract method of IntentService, used to process the services we opened through the startService method, the input parameter Intent is the Intent that enables the service. Here I overwrite a MyService class to process Background transactions. Each call adds 1 to count and prints logs.

Package com. example. intentservicetest; import android. app. intentService; import android. content. intent; import android. util. log; public class MyService extends IntentService {private static final String TAG = MyService. class. getSimpleName (); private int count = 0; public MyService () {super (TAG); // TODO Auto-generated constructor stub} @ Override protected void onHandleIntent (Intent intent) {// TODO Auto-generated method stub // Add the code to be executed here. Intent can save the data we need, // each command sent through Intent will be executed in order count ++; Log. w (TAG, "count:" + count );}}

2. register our service: add our service under the Application tag in the AndroidManifest file.

<service android:name="com.example.intentservicetest.MyService" />

3. enable the Service in external components: here we use Intent loop to enable the Service 10 times in the Activity.

for (int i = 0; i < 10; i++) {        Intent intent = new Intent(MainActivity.this, MyService.class);        startService(intent);}

4. result output:

We can see that in MyService, our request commands are executed in order.

Principle Analysis

1. lifecycle functions:
IntentService also inherits from Service and has the same lifecycle function;

  • OnCreate: called when a service is created;
  • OnStartCommand (Intent, int, int) method: The onStart method is called in the Service source code. Each time a component is called when the service is started using the startService method, two int-type parameters, one is the group identifier and the other is the start ID, the Group identifier indicates whether Intent sends a message once or never succeeded. Each time the onStartCommand method is called, The start ID is different, and the start ID is also used to distinguish different commands;
  • OnDestroy method: called when the service is stopped.

2. onCreate method: first, let's look at the onCreate method in IntentService source code,

    @Override    public void onCreate() {        super.onCreate();        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");        thread.start();        mServiceLooper = thread.getLooper();        mServiceHandler = new ServiceHandler(mServiceLooper);}

We can see that an asynchronous thread HandlerThread is enabled in the onCreate method of IntentService to process our requests, and loose and Handler are used to manage our request command queue. For details about HandlerThread usage, refer to the following blog: Android source code analysis-Handler and logoff mechanism.

3. How to stop the service
After seeing the onCreate method, we can understand how IntentService enables asynchronous threads and manages command queues. As we mentioned before, when the background service finishes processing, we do not need to call the stopService method to destroy the service. IntentService will be destroyed automatically. How can this problem be solved? Let's take a look at 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);        }    }

After processing each command in Handler, The stopSelf (int) method is called to stop the service. This method requires the start ID from the onStartCommand method, the service is stopped only when the latest startup ID is received. That is to say, our IntentService will stop the service until all commands in the command queue are executed.

SetIntentRedelivery Method

In the source code, we can find that this method changes the value of the boolean variable mRedelivery, while the value of mRedelivery is related to the response variable of onStartCommand:

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

As you can see, different mRedelivery will return two different identifiers START_REDELIVER_INTENT and START_NOT_STICKY. What are their differences?
The difference is that if the system disables the service before it completes, the two types are different:

  • The START_NOT_STICKY service is directly disabled, while the START_REDELIVER_INTENT Service tries to start the service again when the available resources are no longer busy.
  • From this we can find that when our operation is not very important, we can choose START_NOT_STICKY, which is also the default option of IntentService. When we think that the operation is very important, select START_REDELIVER_INTENT service.
Non-sticky service and sticky Service

The non-sticky Service stops when it determines that the task is completed. If a Service is a non-sticky Service, the START_REDELIVER_INTENT or START_NOT_STICKY flag should be returned in the onStartCommand method.
The sticky service continues until the external component calls the Context. stopService method. The sticky service returns the flag START_STICKY.

Note: IntentService should not process long-running services (such as music playback). sticky service should be used to complete long-running services.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.