Go to the hardware store to buy a drill, not because we need to drill, we just need to hole, since the hardware store can not buy holes, back and second, buy punch tools. The same for background threads, what we really need is the ability to process outside of the UI main thread, and Android provides an easier and more transparent asynctask for programmers to write background operations.
With Asynctask, you need to create asynctask data, implement the abstract methods in it, and override some methods. With Asynctask we do not need to write the background thread ourselves, without terminating the background thread, such as Stop (). The asynctask approach is not appropriate for an infinite loop, and may be more appropriate to use runnable or thread.
For first-time users, Asynctask seems to have some complications. Let's start by learning the basics of asynctask and then give a small example to verify.
Asynctask
There are three parameters in Asynctask (e.g. class MyTask extends asynctask< parameter 1, parameter 2, parameter 3>{})
- Parameter 1: Passing the type of the parameter to the execution method of the background task
- Parameter 2: During background task execution, the main UI thread is required to process the intermediate state, usually some type of parameter passed in UI processing
- Parameter 3: Parameter types when the background task finishes executing the return
where parameter 1 and parameter 2 are a varags, such as String ..., equivalent to string[].
The steps to use for Asynctask are as follows:
- Create a subclass of Asynctask, with parameters (parameter 1, parameter 2, parameter 3) created with the object
- When the object's Excute () is called, the background process is started and the code for the Doinbackground () is executed. The type of the parameter passed in Excute () is described in Parameter 1, which belongs to the paradigm definition
- If we want some initialization processing to start in the background process, you can override the OnPreExecute () method, noting that the code is executed in the UI thread
- After executing the background process, we need to do some processing, such as stopping the dynamic screen of some UI, the progress bar disappearing and so on, can rewrite the OnPostExecute () method, again, the code is executed in the main thread of the UI. Where the return value of Doinbackground () is passed as the OnPostExecute () parameter, whose type is described by parameter 3
- In a background process, if you need to report a processing state to the UI thread, it can be triggered by publishprogress (), which will execute the rewritten onprogressupdate () code in the UI main thread, where the type of the parameter passed is described by parameter 2.
A small example
There is a small example of a ListView in which there is no content in the list, and a asynctask is gradually added to the list by an entry.
1) XML file: Simple ListView Layout
<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout ... ...>
<listview android:id= "@android: Id/list"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"/>
</LinearLayout>
2) Example code
public class Chapter15test3 extends listactivity{
Here is the list item content, which in this case will be added to the background task individually
private static string[] items={"Lorem", "Ipsum", "dolor", "sit", "Amet", "Consectetuer", "adipiscing", "Elit", "Morbi", " Vel "," Ligula "," Vitae "," Arcu "," Aliquet "," mollis "," Etiam "," Vel "," erat "," Placerat "," ante "," Porttitor "," Sodales "," Pellentesque "," Augue "," Purus "};
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.LAYOUT.CHAPTER_8_TEST2);
In this example, we did not import the items data at first, note that the item data is the new ArrayList, that is, no content
Setlistadapter(New Arrayadapter<string> (this,android. R.layout.simple_list_item_1,new arraylist<string> ()));
Step 5: Create the Background Task object and start the background thread through execute (), call the Code of Doinbackground (), the parameter type in execute is parameter 1, here we do not need to pass any content
New Addstringtask ().Execute();
}
Step 1: Create the Asynctask subclass, parameter 1 is the form type of void, Parameter 2 is the form type of string, and Parameter 3 is void. Where parameter 1: The type of the parameter is passed to the execution method of the background task, and parameter 2: During the background task execution, the main UI thread is required to process the intermediate state, usually some type of parameter passed in UI processing, and Parameter 3: The type of the parameter when the background task finishes executing the return.
Private class Addstringtask extendsAsynctask<void, string,void>{
We add a method of detecting information to print which thread is currently executing the information
private void Printinfo (String info) {
LOG.D ("WEI", Info + ": Tread is" + thread.currentthread (). GetName ());
}
Step 2: Implement the Abstract Method Doinbackground (), the code will execute in the background thread, triggered by execute (), because this example does not need to pass parameters, use void ..., the specific way of writing for the normal form
Protected void/* parameter 3*/Doinbackground(Void ...params/* parameter 1*/) {
for (String Item:items) {
Step 3: Notify the UI main thread to perform related actions (defined in onprogressupdate)
Publishprogress (item/* parameter 2*/);
Printinfo ("Doinbackgound" + Item);
Systemclock.sleep (200);
}
return null;
}
Step 3: Define the content that is executed on the UI main thread after receiving the pushprogress () trigger, in this case, add item to list. The arguments in the method are in the form of a paradigm, in essence an array, because we only pass the item a string to get, for Values[0]
protected voidonprogressupdate(String ...values/* parameter 2*/) {
Printinfo ("Onprogressupdate get param" + values[0]);
((arrayadapter<string>) Getlistadapter ()). Add (Values[0]);
}
Step 4: Define the processing after the background process has finished executing, in this case, using toast
protected voidOnPostExecute(Void result/* parameter 3*/) {
Printinfo ("OnPostExecute");
Toast.maketext (Chapter15test3.this, "done!", Toast.length_short). Show ();
}
}
}
We keep track of where the pieces of code are executed according to Printinfo: Doinbackground is executed in the background thread, onprogressupdate () and OnPostExecute () are executed in the UI thread. Main is the main thread of the UI, and Asynctask #1为后台线程, the name is not the same.
Need to be aware
Although Android provides background tasks for us to handle, whether to use background tasks, and how to use background tasks, we should pay attention to the following content:
There may be interaction between the user and UI in the execution of background threading, which can have a significant impact on background tasks, so you need to notify the background thread that Android provides a lot of classes to handle, encapsulated in the Java.util.concurrent package, to help secure communication with the background thread. Perhaps in the background threading, our activity has been killed, such as a phone call, and then send a text message to view the number book. Then the system may kick your activity, then we will learn the activity life cycle and learn about the situation. In programming, this happens and the background process needs to be closed whenever possible. There may be some kind of error in performing background threading, such as downloading the URL in the background, and the network connection is broken. In this case, shutting down the background process may be the best deal. In addition to the background task is to consume CPU and memory, there is a price, we should ensure that it is more effective when processing.
RELATED links: My Andriod development related articles
Android Learning Note (32): Threads: Background Asynchronous task Asynctask