Android interview, IntentService principle and usage, androidintent
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 finish execution:
Create a project and create a class that inherits the IntentService. Here is IntentServiceDemo. java.
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 onCreate () {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 (boolean 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 {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace () ;}@ Override public void onDestroy () {System. out. println ("onDestroy"); super. onDestroy ();}}
I printed out all the lifecycle methods. Later, let's see how it is executed. Next, the Activity starts IntentService in the Activity:
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 );}}
Finally, do not forget to configure the Service because it inherits from the Service. 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 take a look at the execution results:
I am the dividing line of tiantiao
Reference: http://blog.csdn.net/ryantang03/article/details/8146154
What are the advantages of IntentService in ANDroid?
IntentService is. startService (Intent) starts a Service that can process asynchronous requests. When using this Service, you only need to inherit the IntentService and override the onHandleIntent (Intent) method to receive an Intent object, stop yourself when appropriate (usually when the work is completed ). all requests are processed in one working thread, and they will be executed alternately (but will not block the execution of the main thread). Only one request can be executed at a time.
This is a message-based service. Every time you start this service, it does not process your work immediately, but first creates the corresponding logoff, handler and added the Message object with the client Intent in MessageQueue. When logoff finds a Message, it obtains the Intent object through the onHandleIntent (Intent) msg. obj) to call your processing program. after processing, your services will be stopped. this means that the life cycle of Intent is consistent with that of the task you process. therefore, this type of download task is very good. After the download task is completed, the Service stops and exits.
What should I pay attention to when interviewing android programmers?
What is the difference between Padding and Margin in the UI? The relative completion of the widget is implemented in the lifecycle of the antifraud service. Explain the relationships among Message, Handler, Message Queue, and logoff in the single-thread model. What is the full name of AIDL? How to work? What types of data can be processed? Please explain the difference between the permission for running Android programs and the permission for the file system. Multiple browsers are installed on the system. Can I specify a browser to access a specified page? The use and understanding of multithreading and the passing of handle between multithreading. Understanding of android virtual machines, including memory management mechanism garbage collection mechanism. Framework working method and principle, how the Activity generates a view, and what the mechanism is. Some restrictions of android, such as the apk package size limit and the time limit for reading large files. How to load music information and improve its efficiency. How can ListView improve its efficiency? After the application is started, will the application language change when the system language is changed? Start a program, you can click the icon on the main interface to enter, you can also jump from a program in the past, what is the difference between the two? What is the difference between Android and Java? Task Stack allocation in Android. In Android, how does one save memory usage and actively recycle the memory? Can methods in different projects be called to each other? In Android, how does one determine the phone status, power-off, incoming call, and missed calls in a call record? Dvm processes, Linux processes, and application processes are EF files of the same concept SIM card. How can I determine whether an SD card exists? What are the features of Memory Management in Embedded Operating Systems. What is an embedded real-time operating system? Does the Android operating system belong to a real-time operating system? How many bytes does the longest Short Message count? Cross-process communication in Linux. This article describes how to understand Android NDK. Let's talk about the advantages and disadvantages of Android. In Android, when does GC cause memory leakage? How to refresh the View in the Android UI. A brief description of the Android digital signature. What is ANR and how to avoid it? What are the features and differences of animations in android? The principle of the handler mechanism. In android, how can threads communicate with processes. Let's talk about the principles of the mvc pattern, which is used in android. Which of the following types of xml parsing classes are recommended on android? And their principles and differences. What is the difference between DDMS and TraceView? The res directory has several default resources. Which version of android is a major upgrade? Which of the following methods must be executed when two activities are redirected. The lifecycle of the Activity during horizontal/vertical screen switching. How to Set an Activity as a window style. What should I do if your background Activity is recycled by the system? How to exit the Activity? How can I safely exit the Application that has called multiple activities? If the background Activity is recycled by the system for some reason, How can I save the current status before it is recycled by the system? How do I transmit data between two activities? How can I enable a service when an Activity is started? Can different activities of the same program be stored in different Task stacks? How to bind an Activity to a service, and how to start its own service in the activity? What is a Service and its lifecycle. What are the startup methods and differences between services and how to disable services? No service is required. Page B is used for playing music. It jumps from page A to page B and returns. How can I continue playing music? What is IntentService? What are the advantages? When to use ...... the full text>