Why do you use asynchronous tasks?
We know that the update UI component in Android has to be updated in the UI thread (the main thread), and in order to avoid the UI thread being blocked and unresponsive, Android generally recommends putting time-consuming operations on a new thread, but new threads may also need to dynamically update the UI components. For example, you need to download a picture from the Internet and then display it in ImageView, you should put the link network, get the network data operation in the new thread to complete: the problem is that the new thread will not be allowed to update the UI component directly after acquiring the network resources, this time need to use asynchronous processing.
Asynchronous processing in addition to using the handler class to pass message processing, there is a more lightweight processing asycntask, for simple asynchronous processing, without the use of threading and handler can be implemented
Basic introduction of Asycntask class:
Asycntask<params,progress,result> is an abstract class that is typically used for inheritance, and the class needs to specify the following three generic parameters
Params: Type of input parameter to start task execution
Progress: Progress value type for background task completion
Result: The results type returned by the background execution task completion
Introduction to Asycntask Method:
Doinbackground (Params...param): Using Asycntask must override this method, overriding this method is to put the background thread to complete the task. In this method, you can call Publishprogress (Progress. Values) method to update the execution progress of a task
OnPreExecute (): This method will be called by the system before the background time-consuming operation, that is, before the Doinbackground (Params...param) method, usually in this method to complete some initialization operations, such as the original hidden progress bar display
OnPostExecute (Result result): The system automatically calls this method when the Doinbackground (Params...param) method is executed, and the value returned by the Doinbackground method is passed to the method
Onprogressupdate (): Call publishprogress in the Doinbackground (Params...param) method (Progress.. Values) method automatically calls this method when the task progress is updated
Execute (): an instance object invocation of a subclass of Asycntask that is used to start a time-consuming task
Note the point:
- Asycntask Doinbackground (Params...param), OnPreExecute (), onpostexecute (result result), onprogressupdate () Four methods cannot be called manually by themselves, and these four methods are automatically called by the system after the Execute () method is called.
- The action to perform the UI update cannot be performed in the Doinbackground (Params...param) method, and can be OnPreExecute (), onpostexecute (result result), onprogressupdate () Three methods in any of the one by one methods, but to distinguish the order in which these methods are executed, or even if the UI component is executed, it may be performed without any effect until the time-consuming operation.
- An instance of Asycntask must be created in the UI thread
- Invoking the Execute () method with an instance of Asycntask must be in the UI thread
The following source code features: through the mesh address call to display the picture in the app ImageView, when the picture has not been loaded out before the progress bar, the picture is loaded and hide the progress bar
Activity_main.xml Layout file:
1 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"2 Android:layout_width= "Match_parent"3 Android:layout_height= "Match_parent"4 android:orientation= "vertical">5 6 7 <Button8 9 Android:layout_width= "Match_parent"Ten Android:layout_height= "Wrap_content" One Android:onclick= "BTN" A Android:text= "Submit" /> - - the <ProgressBar - Android:id= "@+id/bar" - Android:layout_width= "Match_parent" - Android:layout_height= "Wrap_content" + android:padding= "20px" - android:visibility= "Gone" /> + A <ImageView at Android:id= "@+id/ima" - Android:layout_width= "Wrap_content" - Android:layout_height= "Wrap_content" /> - - - </LinearLayout>
Activity_main.java Source code:
1 Package Com.contentprovide.liuliu.asynctaskdemo;2 3 import Android.graphics.Bitmap;4 import android.graphics.BitmapFactory;5 import Android.os.AsyncTask;6 import android.support.v7.app.AppCompatActivity;7 import Android.os.Bundle;8 import Android.view.View;9 import Android.widget.Button;Ten import Android.widget.ImageView; One import Android.widget.ProgressBar; A - import Java.io.BufferedInputStream; - import Java.io.BufferedReader; the import java.io.IOException; - import Java.io.InputStream; - import Java.net.URL; - import java.net.URLConnection; + - Public class Mainactivity extends Appcompatactivity { + A ProgressBar Bar; atString url = new String ("Https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1514633107382&di=6811991b77bb94183ecfc91296644c53&imgtype=0&src=http%3a%2f%2fimage.tianjimedia.com%2fuploadimages%2f2014%2f289%2f01%2figs09651f94m.jpg "); - ImageView ima; - - - @Override - protected void OnCreate (Bundle savedinstancestate) { in super.oncreate (savedinstancestate); - Setcontentview (r.layout.activity_main); to ima = (ImageView) Findviewbyid (R.id.ima); + bar = (ProgressBar) Findviewbyid (R.id.bar); - the * } $ Panax Notoginseng Public void btn (view view) { - new Myasynctask (). Execute (URL); The//execute method must be called in the UI thread the } + A //Custom inner class inheritance Asunctask theClass Myasynctask extends Asynctask<String, Void, Bitmap> { + - @Override//execute before the Doinbackground () method $ protected void OnPreExecute () { $ Super.onpreexecute (); - bar.setvisibility (view.visible);//Set progress bar visible - } the - @OverrideWuyi protected Bitmap doinbackground (String ... strings) { the Bitmap Bitmap = null; - try { Wu Thread.Sleep (+); - //Gets the URL value passed in About String url = strings[0]; $ try { - urlconnection urlconnection = new URL (URL). OpenConnection (); - InputStream InputStream = Urlconnection.getinputstream (); - //parse the input stream via Decodestream A bitmap = Bitmapfactory.decodestream (InputStream); + the - } catch (IOException e) { $ e.printstacktrace (); the } the the the } catch (Interruptedexception e) { - e.printstacktrace (); in } the the About return bitmap; the the } the + - @Override the protected void OnPostExecute (Bitmap Bitmap) {Bayi Super.onpostexecute (bitmap); the bar.setvisibility (View.gone);//Setting the progress bar is not visible the Ima.setimagebitmap (bitmap);//Set the image resources from the Internet to ImageView - } - } the the}
Android Asynchronous Task Asynctask