Android Development-Multi-threaded

Source: Internet
Author: User

Several multi-threaded implementations in Android:

1) activity.runonuithread (Runnable)

2) View.post (Runnable); View.postdelay (Runnable, long)

3) Handler

4) Asynctask

Introduction to Asynctask notation

The multitasking model with asynchronous task schemas is not really robust enough to create multiple asynctask instances. A asynctask is executed only once and cannot be executed repeatedly, fast-food class threads, run out at once.

Implement Asynctask subclass, the most important two methods, one is doinbackground (params); one is onpostexecute (result). In the Doinbackground () method, the time-consuming transaction is processed and the result is returned, the returned value is taken as a parameter in the OnPostExecute method, and the result can be displayed on the UI in OnPostExecute ().

Steps:

① Instantiation of Asynctask:

Instantiate Asynctask then pass task.exec (Pamas); Pass in the parameter, this parameter list is dynamic, can be one can also make multiple, length variable.

Asynctask<params,values,reslut> The first parameter is passed in the method Doinbackground (params), the second parameter is the value of the data update, and the third is the result of processing the return of the transaction.

②onpreexecute Method:

This method has no parameters and no return value, so you can do some reminders in this method. Like show a dialog, or play a toast and tell the user to start the download.

③doinbackground (params) method:

Enter the ASYNCTASK internal structure, first will execute the Reslut doinbackground (params) method, this method will handle the time consuming transaction, exec () parameters will be passed into this method to do parameters, and the return value will be as OnPostExecute () The parameters. If you want to update your progress, you need to execute the publicprogress () method.

④onprogressupdate (values) method:

The parameter of this method must execute the Publicprogress () method in the Doinbackground () method, this method will pass the parameter into the Onprogressupdate () method, then can do some UI update display in this method, For example, the value of the progress bar can be changed dynamically through this values value.

⑤onpostexecute (Result) method:

Here is the way the transaction is completed, and the results of the Doinbackground method execution will be uploaded here, if the method returns data. The UI can be handled in this way, and the processed data can be displayed on the UI. than a piece of text Ah, everything you want results.

Case List

1. Add Android Project files

2, add class inherit Asynctask, project file as follows

    

Displaying Data in a ListView

3, add layout files, layout as follows

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.example.multithreadind01.MainActivity" > <TextView Android:id= "@+id/textview1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/hello_world"/> <Button Android:id= "@+id/button1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignparentright= "true"Android:layout_aligntop= "@+id/textview1"Android:layout_marginright= "53DP"Android:text= "button"/> <ListView Android:id= "@+id/listview1"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:layout_below= "@+id/button1"Android:layout_margintop= "84DP" > </ListView> <ProgressBar Android:id= "@+id/progressbar1"style= "? Android:attr/progressbarstylehorizontal"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignleft= "@+id/listview1"Android:layout_alignright= "@+id/button1"Android:layout_below= "@+id/button1"Android:layout_margintop= "28DP"/></relativelayout>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "Horizontal" > <TextView Android:id= "@+id/username"Android:layout_weight= "1"Android:layout_width= "Match_parent"Android:layout_height= "60DP"android:textsize= "45DP"/> <TextView Android:id= "@+id/sex"Android:layout_weight= "1"Android:layout_width= "Match_parent"Android:layout_height= "60DP"android:textsize= "45DP"/></linearlayout>

Mainactivity Class Code: Binding Data

 Public classMainactivityextendsActivity {PrivateString fromdb_str1 = ""; PrivateButton btn; PrivateTextView TV; PrivateListView LV; PrivateBaseadapter Adapter; PrivateList<user> userlist =NewArraylist<user>(); @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r.layout.activity_main);         for(inti = 0; I < 5; i++) {User u=NewUser (); U.setusername ("Xiao Ming" +i); U.setsex ("Female" +i);        Userlist.add (U); } TV=(TextView) Findviewbyid (R.ID.TEXTVIEW1); BTN=(Button) Findviewbyid (R.id.button1); Btn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {mytask Mt=NewMyTask (mainactivity. This); Mt.execute (userlist,adapter);//the parameters inside are passed to Doinbackground.                /*Thread t1 = new Thread (new Runnable () {@Override public void Ru                    N () {fromdb_str1 = "test";                }                });                T1.start ();                Tv.settext (FROMDB_STR1); */                            }        }); Adapter=NewBaseadapter () {@Override Public intGetCount () {//TODO auto-generated Method Stub                returnuserlist.size (); } @Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {Layoutinflater Inflater= Mainactivity. This. Getlayoutinflater ();                View view; if(convertview==NULL) {View= Inflater.inflate (R.layout.item,NULL); }                Else{View=Convertview; } TextView tv_username=(TextView) View.findviewbyid (r.id.username); TextView Tv_sex=(TextView) View.findviewbyid (r.id.sex);                Tv_username.settext (Userlist.get (position). GetUserName ());                Tv_sex.settext (Userlist.get (position). Getsex ()); returnview; } @Override PublicObject GetItem (intposition) {                //TODO auto-generated Method Stub                return NULL; } @Override Public LongGetitemid (intposition) {                //TODO auto-generated Method Stub                return0;        }        }; LV=(ListView) Findviewbyid (R.ID.LISTVIEW1);    Lv.setadapter (adapter); }}

MyTask class, applying multi-threading, displaying data

 Packagecom.example.multithreadind01;Importjava.util.List;ImportAndroid.os.AsyncTask;ImportAndroid.view.View;ImportAndroid.widget.BaseAdapter;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMyTaskextendsAsynctask {PrivateBaseadapter Adapter; PrivateList<user>userlist; Privatemainactivity activity;  PublicMyTask (mainactivity activity) { This. Activity =activity; }        //1. All time-consuming code, written here (database, Bluetooth, Web services)//2. Never touch the UI@Overrideprotectedobject Doinbackground (Object ... params) {userlist= (list<user>) params[0]; Adapter= (Baseadapter) params[1];  for(inti = 0; I < userlist.size (); i++) {            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } userlist.get (i). Setusername ("Little Red" +i); Userlist.get (i). Setsex ("Male" +i);        Publishprogress (i); }                        //Userlist,adapter//back to front end        return"Weather: 22 degrees"; }        //Prepare@Overrideprotected voidOnPreExecute () {Toast.maketext (activity,"Good night.", Toast.length_short). Show (); }        //done after the execution@Overrideprotected voidOnPostExecute (Object result) {String R=result.tostring (); TextView TV=(TextView) Activity.findviewbyid (R.ID.TEXTVIEW1); Tv.settext ("Access is complete! "+R); }        //Step through@Overrideprotected voidonprogressupdate (Object ... values) {//TODO auto-generated Method Stub//0,1,2,3,4        intBar = Integer.parseint (values[0].tostring ()); Bar= (bar+1) *20; ProgressBar ProgressBar=(ProgressBar) Activity.findviewbyid (R.ID.PROGRESSBAR1);        Progressbar.setprogress (bar);    Adapter.notifydatasetchanged (); }}

: Start interface, in progress, when finished

To write an Android project, we should take a step-by-step, a function of a function to test, rather than write it all again to test, so out of the wrong words, find fault do not know how to find, should be stable,

Mistakes are easy to find and efficiency is high.

  

Android Development-Multi-threaded

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.