Android has a built-in asynchronous class, which encapsulates asynchronous operation methods, mainly including three operation methods.
1. doinbackground this is a program running in the background, that is, a new thread is created to run content in the background, such as (obtaining images through the network)
2. onprogressupdate is an update on the front-end interface. To reflect background operations to the front-end, you need to process them here, for example (refresh the front-end image)
3. onpostexecute: This is the processing done after the thread ends.
Here we divide Asynchronization into three steps. Well, let's talk about it later. Let's take a look at the program running today. The program will add one item every second, as shown in the figure below.
Okay. Next, let's analyze the implementation of the Code:
Public class asyndemo extends activity {private string [] items = {"first item", "second item", "third item", "fourth item", "fifth item ", "Item 6", "Item 7", "item 8", "item 9", "Item 10"}; private listview; @ overrideprotected void oncreate (bundle savedinstancestate) {// todo auto-generated method stubsuper. oncreate (savedinstancestate); setcontentview (R. layout. asyn_layout); listview = (listview) findviewbyid (R. id. list); // set the listview adapter listview. setadapter (New arrayadapter <string> (this, android. r. layout. simple_list_item_1, new arraylist (); // run the asynchronous program New addstringtask(cmd.exe cute () ;}/ *** asynchronous class, inherited asynctask **/class addstringtask extends asynctask <void, String, void> {// the program running in the background @ overrideprotected void doinbackground (void... arg0) {// traverse the items array and send each string to the foreground for (string S: Items) {publishprogress (s); systemclock. sleep (1000);} return NULL;} // Add the data to the adapter @ overrideprotected void onprogressupdate (string... values) {(arrayadapter) listview. getadapter ()). add (Values [0]);} // end @ overrideprotected void onpostexecute (void result) {toast. maketext (asyndemo. this, "end", 1 ). show ();}}}
In fact, this is the code. The specific steps are as follows. I believe everyone can understand it.