Simple use of Android asynchronous class Asynctask

Source: Internet
Author: User

Android to reduce this development difficulty, provides the asynctask. Asynctask is a packaged background task class, as its name implies, an asynchronous task, more commonly a thread that performs a background task

And he will automatically notify the main thread to update the UI

Advantages:

The structure is clear and easy to understand.

Disadvantages

Slightly larger code size

Look directly at the code below

1 Private classAsyncloginextendsAsynctask<void,integer,boolean>{2         PrivateEditText Passwordedit;3         PrivateEditText Studentidedit;4          Public BooleanIsclose=false; constructor function5          PublicAsynclogin (EditText passwordedit, EditText studentidedit) {6             Super();7              This. Passwordedit =Passwordedit;8              This. Studentidedit =Studentidedit;9         }Ten          One         Private BooleanCheckresultcode (String code) { AString message=Codetoresult.get (code); -             if(Dialog.isshowing ()) - Dialog.dismiss (); the             if(message==NULL){ -                 return true; -}Else{ -Toast.maketext (mainactivity. This,      + message, - Toast.length_long). Show ();  +                 return false; A             } at         } -          -         Private voidIntentjump () { -             if(!isclose) { -Intent Intent =NewIntent (mainactivity. This, Courselistactivity.class); -Intent.putextra ("SessionId", mainactivity. This. sessionId); inIntent.putextra ("strUserName", This. Studentidedit.gettext (). toString ()); -Mainactivity. This. StartActivity (intent); toMainactivity. This. Finish (); +             } -         } theThis method is called after the background thread completes, and the main thread UI can be updated in this method * @Override $         protected voidOnPostExecute (Boolean result) {Panax Notoginseng             Super. OnPostExecute (result); -             if(Result) { the                 if(Checkresultcode (mainactivity. This. SessionId)) + intentjump (); A}Else{ theCheckresultcode ("000"); +             } -         } $Background tasks, mainly to complete the task of heavy workload $ @Override -         protectedBoolean doinbackground (Void ... params) { -String sessionid= ""; the              -             Wuyi             Try{ theThread.Sleep (5000); -SessionId =Webservice.checklogin ( Wu                          This. Studentidedit.gettext (). toString (), -                          This. Passwordedit.gettext (). toString ()); About}Catch(Exception e) { $ e.printstacktrace (); -                 return false; -             } -Mainactivity. This. sessionid=sessionId; A             return true; + }//Call this method before starting execution the @Override -         protected voidOnPreExecute () { $             Super. OnPreExecute ();  theDialog =NewProgressDialog (mainactivity. This);  theDialog.setcancelable (true); theDialog.setmessage ("Logging in, please wait ..."); theDialog.setoncancellistener (NewDialoginterface.oncancellistener () { - @Override in                  Public voidonCancel (Dialoginterface dialog) { the                     if(asyclogin!=NULL) theAsyclogin.cancel (true); About                 } the              }); the dialog.show (); the         } +}

New Asynclogin (Passwordedit,studentidedit). Execute ();//Start Task

Here is the interface method

1, Doinbackground (Params ...) background execution, more time-consuming operations can be placed here. Note You cannot manipulate the UI directly.

2. OnPostExecute (Result) handles the UI in such a way that it can use the results processed in Doinbackground to manipulate the UI.

3, Onprogressupdate (Progress ...) You can use the progress bar to increase user experience. This method executes on the main thread and is used to show the progress of the task execution.

4, OnPreExecute () This method is called before the task executes, and you can display the progress dialog box here as if it were the code above.

5, oncancelled () when the user calls Cancel, call the method

Precautions

An instance of Asyntask must be created in the UI thread.

Do not actively invoke any interface methods.

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.