Android interview and IntentService principles and usage

Source: Internet
Author: User

Android interview and IntentService principles and usage
In Android development, we may encounter such a business requirement. A task is divided into several subtasks, which are executed in sequence. After all the subtasks are executed, this task is successful. This can be achieved by using several sub-threads for sequential execution, but each thread must be manually controlled, and another sub-thread must be enabled after one sub-thread completes execution. Or, put them all in one thread for sequential execution. This can be done in this way. However, if this is a background task, you have to put it in the Service. Because the Service and Activity are of the same level, you need to execute time-consuming tasks, you have to open a sub-thread in the Service for execution. Is there a simple way to deal with this process? The answer is IntentService. What is IntentService? IntentService is a class that inherits from the Service and processes asynchronous requests. There is a working thread in IntentService to process time-consuming operations. The method for starting IntentService is the same as that for starting traditional services, at the same time, after the task is executed, IntentService will automatically stop without manual control. In addition, IntentService can be started multiple times, and each time-consuming operation is executed in the onHandleIntent callback method of IntentService in the form of a work queue, and only one working thread is executed at a time, after the execution is completed, the first execution is followed by the second execution, and so on. All requests are in a single Thread and will not block the main Thread (UI Thread) of the application. Only one request is processed at a time. So what are the benefits of using IntentService? First, we save the trouble of manually opening threads in the Service. Second, when the operation is completed, we do not need to manually stop the Service. Code next let's take a look at how to use it. I wrote a Demo to simulate two time-consuming operations, Operation1 and Operation2. To execute Operation1 and Operation2 first, 1 and 2 must wait for 1 to run: Create a project, create a new class that inherits the IntentService. Here is the IntentServiceDemo. java replication code public class IntentServiceDemo extends IntentService {public IntentServiceDemo () {// The constructor super ("IntentServiceDemo") of the parent class must be implemented;} @ Override public IBinder onBind (Intent intent) {System. out. println ("onBind"); return super. onBind (intent) ;}@ Override public void onC Reate () {System. out. println ("onCreate"); super. onCreate () ;}@ Override public void onStart (Intent intent, int startId) {System. out. println ("onStart"); super. onStart (intent, startId) ;}@ Override public int onStartCommand (Intent intent, int flags, int startId) {System. out. println ("onStartCommand"); return super. onStartCommand (intent, flags, startId) ;}@ Override public void setIntentRedelivery (B Oolean enabled) {super. setIntentRedelivery (enabled); System. out. println ("setIntentRedelivery");} @ Override protected void onHandleIntent (Intent intent) {// Intent is sent from Activity and carries the identification parameter, execute different tasks String action = intent according to different parameters. getExtras (). getString ("param"); if (action. equals ("oper1") {System. out. println ("Operation1");} else if (action. equals ("oper2") {System. out. println ("Operation2");} try {Thr Ead. sleep (2000);} catch (InterruptedException e) {e. printStackTrace () ;}@ Override public void onDestroy () {System. out. println ("onDestroy"); super. onDestroy () ;}} I printed out all the lifecycle methods by copying the code. Let's take a look at how it is executed. Next, the Activity starts IntentService in the Activity: copy the code public class TestActivity extends Activity {/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // It Can Be Started multiple times. Each time it is started, a new work thread will be created, however, there is always only one IntentService instance // Operation 1 Intent startServiceIntent = new Intent ("com. test. intentservice" ); Bundle bundle = new Bundle (); bundle. putString ("param", "oper1"); startServiceIntent. putExtras (bundle); startService (startServiceIntent); // Operation 2 Intent startServiceIntent2 = new Intent ("com. test. intentservice "); Bundle bundle2 = new Bundle (); bundle2.putString (" param "," oper2 "); startServiceIntent2.putExtras (bundle2); startService (startServiceIntent2, do not forget to configure the Service because it inherits from Servic. E. Therefore, it is still a Service and must be configured. Otherwise, it does not work. At first I forgot, and the result was half a day unresponsive. <Service android: name = ". intentServiceDemo "> <intent-filter> <action android: name =" com. test. intentservice "/> </intent-filter> </service> Finally, let's look at the execution result: 1. From the result, we can see that the onCreate method is executed only once, the onStartCommand and onStart methods are executed twice, and two Work threads are enabled. This confirms that as mentioned earlier, there are only one IntentService instance, this is the same as the traditional Service. Operation1 was printed prior to Operation2, And I paused the two operations for 2 s, and onDestroy destroyed the IntentService.

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.