Android notes. Service components (3). Use IntentService and androidintent

Source: Internet
Author: User

Android notes. Service components (3). Use IntentService and androidintent
Use IntentService reprint please indicate the source: http://blog.csdn.net/u012637501 (embedded _ small J of the sky)
1. service defects because the Service itself has the following two problems: (1) the Service does not start a separate process, and the Service and its application are located in the same process; (2) the Service is not a new thread. If we directly process time-consuming tasks in the Service, the application may be "stuck ". If we need to process time-consuming tasks in the Service, we can also start a new thread in the onCreate () method of the Service to process the time-consuming task (for example, above ). However, the problem arises. The Activity that starts the Service may be exited by the user at any time. If the sub-thread is not finished, the Activity has been exited by the user, at this time, the processes where the sub-threads are located become empty processes (that is, processes without any active components). When the system needs memory, the process may be terminated first. If the host process is terminated, all the sub-threads in the process will also be terminated, which may cause the sub-threads to fail to be executed.2. IntentService PrincipleIntetnService is a sub-class of Service. It is not a common Service and uses IntentService to make up for the two shortcomings mentioned above. IntentService mainly uses a queue to manage the Intent request. Whenever the client code starts the IntentService through the Intent request, IntentService adds the Intent to the queue and starts a new worker thread to process the Intent. For Asynchronous startService () requests, IntentService processes Intent in sequence in the queue. This thread ensures that only one Intent is processed at the same time. Because IntentService uses a new worker thread to process Intent requests, IntentService does not block the main thread, and all intentservices can process time-consuming tasks by themselves.3. IntentService features(1) IntentService creates a separate worker thread to process all Intent requests. (2) IntentService creates a separate worker thread to process the Code implemented by the onHandleIntent () method, therefore, developers do not need to deal with multi-line issues. (3) When all requests are processed, IntentService will stop automatically. Therefore, developers do not need to call the StopSelf () method to stop the Service. (4) provides the default implementation for the onBind () method of the Service, and the ind () method returns null; (5) provides the default implementation for the onStartCommand () method of the Service, this implementation adds the request Intent to the queue. Note: to extend the IntentService implementation, you do not need to override the onBind () and onStartCommand () methods. You only need to override the onHandleIntent () methods.4. Source Code practiceImplementation: Start the common Service and IntentService respectively, and process time-consuming tasks at the same time to compare the effects of the two.
(1) \ src \ com \ example \ android_intentservice \ ServiceAndIntentService. java implementation: Use two buttons to start the common Service and IntentService

Package com. example. android_intentservice; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; public class ServiceAndIntentService extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main);} // 1. public void startService (View source) {Intent intent = new Intent (this, MyService. class); // create the Intent startService (intent) of the service to be started; // start the specified Service} // 2. method for enabling IntentService: public void startIntentService (View source) {Intent intent = new Intent (this, MyIntentService. class); startService (intent );}}
(2) Implement \ res \ layout \ main. xml: Set the android: onClick attribute of the Button and bind the response method to the Button.
...... <Button android: onClick = "startService" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Start common Service"/> <Button android: onClick = "startIntentService" android: layout_width = "186dp" android: layout_height = "wrap_content" android: text = "Start IntentService"/>
(3) \ src \ com \ example \ android_intentservice \ MyService. java implementation: implement a common Service to execute time-consuming tasks (20 s), and observe whether the ANR exception (Application Not Responding) is caused)
Package com. example. android_intentservice; import android. app. service; import android. content. intent; import android. OS. IBinder; public class MyService extends Service {@ Override public IBinder onBind (Intent intent) {return null ;}// when the Service is started, call this method to execute the corresponding code @ Override public int onStartCommand (Intent intent, int flags, int startId) {long endTime = System. currentTimeMillis () + 20*1000; System. out. println ("onStart"); while (System. currentTimeMillis () <endTime) {synchronized (this) {try {wait (endTime-System.currentTimeMillis ();} catch (Exception e) {}} System. out. println ("--- normal Service time-consuming task execution completed ---"); return START_STICKY ;}}( 4) \ src \ com \ example \ android_intentservice \ MyIntentService. java Implementation: Implement an IntentService to execute time-consuming tasks (20 s), and check whether the ANR exception is caused by package com. example. android_intentservice; import android. app. intentService; import android. content. intent; public class MyIntentService extends IntentService {public MyIntentService () {super ("MyIntentService ");} // IntentService uses a separate thread to execute the method code @ Override protected void onHandleIntent (Intent intent) {// This method can execute any time-consuming tasks, such as downloading files, the thread is paused for 20 s long endTime = System. currentTimeMillis () + 20*1000; System. out. println ("onStart"); while (System. currentTimeMillis () <endTime) {synchronized (this) {try {wait (endTime-System.currentTimeMillis ();} catch (Exception e) {}} System. out. println ("--- IntentService time-consuming task execution completed ---");}}
(5) AndroidManifest. xml implementation: Configure <service ../> information for MyService and MyIntentService in the project file.
<Application android: allowBackup = "true" android: icon = "@ drawable/ic_launcher" android: label = "@ string/app_name" android: theme = "@ style/AppTheme"> <activity .......... </activity> <! -- Configure service --> <service android: name = ". MyService"/> <service android: name = ". MyIntentService"/> </application>
Effect demonstration: a. Effect of clicking "Start common service"
B. The effect of clicking "Start IntentService" 7 times in a row

Sublimation Notes: 1. A common Service executes time-consuming tasks in the onStartCommand () method. IntentService executes time-consuming tasks in the onHandleIntent () method. 2. when a common Service does not create a new thread, the time-consuming task is mainly completed in the main thread of the application. Because the execution of a common Service blocks the main thread, therefore, starting the Service to execute time-consuming tasks may cause ANR exceptions in the program; 3. intentService mainly uses a queue to manage the Intent request. Whenever the client code starts the IntentService through the Intent request, IntentService adds the Intent to the queue and starts a new worker thread to process the Intent. Because IntentService uses a separate thread to complete this time-consuming task, starting MyIntentService will not block the foreground thread and the program interface will not lose response.
Reference: http://wear.techbrood.com/reference/android/app/Service.html

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.