Android note 26. Android asynchronous Task Processing (AsyncTask),. androidasynctask

Source: Internet
Author: User

Android note 26. Android asynchronous Task Processing (AsyncTask),. androidasynctask
Reprinted please indicate Source: http://blog.csdn.net/u012637501 (embedded _ small J of the sky)
I. IntroductionWe know that the Android UI thread is mainly responsible for handling users' button events, user touch screen events, and Screen Drawing events. Other operations should not be implemented in the UI thread as far as possible, these operations may block the UI thread. For example, some time-consuming operations may cause the UI interface to stop responding, thus reducing the user experience. Therefore, in order to avoid UI thread response loss, Android recommends that time-consuming operations be completed in a new thread, but the new thread may also need to dynamically update the UI component: for example, You need to obtain a webpage from the Internet, then, the source code of TextView is displayed. In this case, the operations to connect to the network and obtain network data (Time consumed) should be completed in the new thread. However, the question is: how can we update the UI component data after obtaining network data because the new thread cannot directly update the UI component? To solve the problem that new threads cannot update UI components, Android provides the following solutions: (1) Use the Handler message passing mechanism to implement inter-thread communication (as described in the previous article); (2) activity. runOnUiThread (Runnable); (3) View. post (Runnable); (4) View. postDelayed (Runnable long); (5) asynchronous task. And because (2 )~ (4) programming may be complicated, while asynchronous tasks can simplify this operation.II. Introduction to AsyncTaskAndroid AsyncTask encapsulates inter-thread communication and provides a simple programming method for background and UI threads to communicate: Background threads execute asynchronous tasks and notify the UI of operation results. You can complete asynchronous operations and refresh the user interface without the child thread and Handler.1. AsyncTask classAsyncTask <> is an abstract class, which is usually used for inheritance. When inheriting AsyncTask, you must specify the following three generic parameters: (1) Params: the type of input parameters for task startup execution; (2) Progress: the type of the Progress value (percentage) of the background task completion; (3) Result: the type of the Result returned after the background task is completed, such as String and Integer;2. Main methods in the Async class(1) onPreExecute (): This method will be called by the UI thread before the actual background operation is executed. You can make some preparations in this method, such as displaying a progress bar on the interface or instantiating some controls. This method does not need to be implemented. ----- (UI thread call, background thread not started, initialization work) (2) doInBackground (Params... values): runs the onPreExecute method immediately after it is executed. This method runs in the background thread. Here, we will be mainly responsible for the time-consuming background processing. You can call publishProgress () to update the task progress in real time. This method is an abstract method and must be implemented by sub-classes. ----- (Background thread call to execute background tasks)
(3) onProgressUpdate (Progress... values): After the publishProgress method is called, the UI thread will call this method to display the progress of the task on the interface, for example, through a progress bar. ----- (UI thread call, showing the progress of background tasks)
(4) onPostExecute (Result): After doInBackground is executed, the onPostExecute method will be called by the UI thread, and the background computing Result (doInBackground method return value) will be passed to the UI thread through this method, and displayed to the user on the interface. ----- (UI thread call, display the running result of the background thread) (5) onCancelled (): called when the user cancels the thread operation. It is called when onCancelled () is called in the main thread. ----- (UI thread call, cancel background thread)Iii. asynchronous task processing development steps1. Create a subclass of AsyncTask and specify the type for the three generic parameters. If you do not need to specify a type for a generic parameter, set it to Void. 2. Implement AsyncTask in the preceding five methods as needed; 3. Call execute (Params... params) of the AsyncTask subclass instance to start time-consuming tasks. In addition, the following guidelines must be observed when the AsyncTask class is used: (1) the Task instance must be created in the UI thread; (2) execute (Params ...) methods must be called in the UI thread; (3) do not manually call onPreExecute (), onPostExecute (Result), doInBackground (Params ...), onProgressUpdate (Progress ...) these methods need to be instantiated in the UI thread to call the task; (4) the task can only be executed once; otherwise, an exception will occur during multiple calls.4. Source Code practice1. Implement Functions2. Source Code Implementation(1) MainActivity. javaFunction: gets interface components, instantiate an AsyncTask sub-class object, and call its exeute (Integer... params) method to run a task with the specified parameter params.

Package com. example. android_asynctask; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. progressBar; import android. widget. textView; public class MainActivity extends Activity {private Button downbtn; private TextView textView; private ProgressBar progressBar; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); downbtn = (Button) findViewById (R. id. download); textView = (TextView) findViewById (R. id. text); progressBar = (ProgressBar) findViewById (R. id. progressBar); final DownloadTest download = new DownloadTest (textView, progressBar); // obtain a DownloadTest object and pass the component object parameter downbtn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {download.exe cute (200 );}});}}
(2) DownloadTest. javaFunction: inherits from the AsyncTask subclass. onPreExecute () serves to initialize the running background thread (sub-thread), run the background thread in the doInBackground method, and update the UI in the onProgressUpdate method; the onPostExecute method processes the running results of background threads.
Package com. example. android_asynctask; import android. graphics. color; import android. OS. asyncTask; import android. view. view; import android. widget. progressBar; import android. widget. textView; public class DownloadTest extends AsyncTask <Integer, Integer, String> {private TextView TV; private ProgressBar pb; // DownloadTest (TextView text, ProgressBar bar) {this. TV = text; this. pb = bar;} // The construction method DownloadTest () {}/ * 1 without parameters. the onPreExecute Method * indicates the initialization content of the sub-thread (background) */protected void onPreExecute () {TV. setVisibility (View. VISIBLE); // set the pb of the displayed text component. setVisibility (View. VISIBLE); // set the display progress bar super. onPreExecute ();}/* 2. the doInBackground Method * runs a background thread that calls the onProgressUpdate method every arg0 [0] milliseconds */protected String doInBackground (Integer... arg0) {for (int I = 0; I <100; I ++) {publishProgress (I); // call the onProgressUpdate method and pass the parameter I try {Thread. sleep (arg0 [0]); // accumulate once, thread sleep argo [0] millisecond} catch (InterruptedException e) {e. printStackTrace () ;}} return "download completed"; // The value returned after the backend sub-thread finishes running}/* 3. onProgressUpdate Method * Call publishProgress (I) and pass the parameter I to the parameter values [0] */@ Override protected void onProgressUpdate (Integer... values) {pb. setProgress (values [0]); // sets the progress bar value TV. setText ("downloaded" + values [0] + "%"); // The Text Component displays the prompt information "super. onProgressUpdate (values);}/* 4. onPostExecute * results obtained by processing the background thread **/protected void onPostExecute (String result) {pb. setVisibility (View. INVISIBLE); // hide the progress bar TV. setVisibility (View. VISIBLE); // display the UI text display box component TV. setText (result); TV. setTextSize (20); TV. setTextColor (Color. RED); super. onPostExecute (result );}}


Demo:

Source code analysis: the source code shows that the main thread calls the onPreExecute method of the AsyncTask subclass by calling the execute () method of the AsyncTask subclass, it is used to initialize related content for the background thread before it is run again. Then, call the doInBackground () method in the newly created child thread to implement the background thread function and call the onProgressUpdate () method to update the UI content through the publishProgress () method, finally, execute the onPostExecute method in the main line to process the results of background thread running. Note: Only the doInBackground () method and the publishProgress () method are executed in the Child thread. Other methods are executed in the main thread, therefore, you can update the interface components in these 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.