Android's Asynctask

Source: Internet
Author: User

Android's Asynctask
1.AsyncTask from the quoted package Android.os, it is a class that Android gives us to handle asynchronous tasks. This class enables asynchronous processing to finalize the UI update.
2. For Android UI update, only in the main thread process update, this reason already in front (Android message mechanism handler) introduced, so the rest can only be updated through the child thread or asynchronous. Updates to the child threads are described earlier, and only the updates made by the Async methods are described here.
3. For the reasons why asynchronous updates are being used and whether UI performance is degraded, it is quite certain that a new thread will also consume resources if you do not have to process some time-consuming operations asynchronously, which can also be time consuming. And for child threads to be synchronized with the UI, that is, if the UI is to be processed before it is destroyed, it is easy to have a null pointer or the UI has ended the child thread is still running. This is not the case for asynchronous processing. Instructions are shown below.
4.AsyncTask Introduction:
(1) Public abstract class Asynctask<params, Progress, result>
Params: The starting task is asynchronous processing of the parameter Doinbackground (params ... params)
Progress: Type of progress value returned in background task execution, onprogressupdate (Progress ... values)
Result: The type of the result returned after the background task execution completes, onpostexecute (result result)
(2) Some ways to explain:
OnPreExecute: Some initialization required before performing the background, this method is subordinate to the main thread
Doinbackground: Asynchronous task processing, the time-consuming operation is completed in this method, and the execution of this method is done on the child thread.
OnPostExecute: When the Doinbackground method is complete, the system calls this method automatically and passes the value returned by the Doinbackground method to this method for updating the UI, which is subordinate to the main thread.
Onprogressupdate: After you call the Publishprogress method in the Doinbackground method to update the progress of the task execution, use this method to know the progress of the task.
Publishprogress: This method is used when publishing progress, and when the Async method Doinbackground calls this method, Onprogressupdate is called back.
(3) Publishprogress The working source of this method can explain why asynchronous processing is secure:

@WorkerThreadprotected Final voidpublishprogress (Progress ... values) {if(!iscancelled ()) {gethandler (). Obtainmessage (Message_post_progress,NewAsynctaskresult<progress> ( This, values)).         Sendtotarget (); }     }     Private StaticHandler Getmainhandler () {synchronized(Asynctask.class) {             if(Shandler = =NULL) {Shandler=NewInternalhandler (Looper.getmainlooper ()); }             returnShandler; }     }     Private Static classInternalhandlerextendsHandler { PublicInternalhandler (Looper Looper) {Super(Looper); } @SuppressWarnings ({"Unchecked", "Rawuseofparameterizedtype"}) @Override Public voidhandlemessage (Message msg) {Asynctaskresult<?> result = (asynctaskresult<?>) Msg.obj; Switch(msg.what) { CaseMessage_post_result://there is only one resultResult.mTask.finish (Result.mdata[0]);//This method of execution is the current Asynctask's own finish (). This is exactly what it means to execute finish () in the main thread after the Doinbackground () of the worker thread is executed normally .                      Break; }         }     }


The entire process can be described at the time of the update progress, the object Lock (Asynctask.class), after the completion of the asynchronous and then execute the finish method in the thread, then there will be no interface destroyed when the component is still in work.

5. The following demo demonstrates a typical asynchronous processing power: loading a picture.

 PackageCom.example.testactivityb;ImportJava.io.BufferedInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.net.URL;Importjava.net.URLConnection;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {PrivateImageView ImageView; PrivateTextView TextView; Private StaticString URL = "Http://pic1.sc.chinaz.com/files/pic/pic9/201808/zzpic13515.jpg"; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);         Setcontentview (R.layout.activity_main); ImageView=(ImageView) Findviewbyid (r.id.image); TextView=(TextView) Findviewbyid (R.id.textview); Textview.settext ("Hello World,after a moment,it would disapear"); LOG.D ( This. toString (), "OnCreate main thread"); //Start processing asynchronous tasks by calling the Execute method. Equivalent to the Start method in the thread.         Newmyasynctask (). Execute (URL); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.activity_main, menu); return true; }     classMyasynctaskextendsAsynctask<string,void,bitmap> {         //OnPreExecute: Operation before asynchronous processing, this method is still in the main thread@Overrideprotected voidOnPreExecute () {Super. OnPreExecute ();             Thread.dumpstack (); LOG.D ( This. toString (), "OnPreExecute ..."); //the TextView is set to visible here, which means that you can set UI-related actions heretextview.setvisibility (view.visible); }         //Doinbackground: Asynchronous task processing, another thread is opened.@OverrideprotectedBitmap doinbackground (String ... params) {LOG.D ( This. toString (), "Doinbackground ..."); //get the arguments passed inString URL = params[0]; Bitmap Bitmap=NULL;             URLConnection connection;             InputStream InputStream; Try{Connection=NewURL (URL). OpenConnection ();//The URL object opens the connection with OpenConnection (), obtains the URLConnection class object, and connects using the Connect () method of the URLConnection class object.InputStream = Connection.getinputstream ();//An input stream the reads from this open connection//in order to see more clearly the wait operation to load the picture, the child thread is dormant.Thread.Sleep (4000); Bufferedinputstream bis=NewBufferedinputstream (InputStream); Bitmap= Bitmapfactory.decodestream (bis);//parsing an input stream with the Decodestream methodInputstream.close ();             Bis.close (); } Catch(IOException e) {e.printstacktrace (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }             returnbitmap; }         //OnPostExecute for UI updates. The parameter for this method is the value returned by the Doinbackground method.@Overrideprotected voidOnPostExecute (Bitmap Bitmap) {Super. OnPostExecute (bitmap); LOG.D ( This. toString (), "OnPostExecute ..."); //action on the UI, at which point the bitmap is the result of doinbackground processing. textview.setvisibility (View.gone);         Imageview.setimagebitmap (bitmap); }     }    }

The execution process is as follows:

08-16 10:38:04.102  8437  new sinstance = [email protected], context = [email protected], UserId = 0 08-16 10:38:04.159  8437  8437 D [email protected]: onCreate main thread  08-16 10:38:04.161  8437  843708-16 10:38:04.166  8437  845008-16 10:38:04.285  1475  1536 I Activitymanager:displayed com.example.testactivityb/. Mainactivity: +08-16 10:38:08.506  8437  8437 D [email protected]: OnPostExecute ...

Android's Asynctask

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.