Android Note 26. Android Asynchronous task processing (asynctask)

Source: Internet
Author: User

reprint Please indicate source:http://blog.csdn.net/u012637501( embedded _ small J Sky )
First, Introduction    We know Android ui thread is primarily responsible for Handle the user's key event , User Touch screen event and screen drawing event And so on, for other operations try not to implement in the UI thread, because these operations are likely to block the UI thread, such as some time-consuming operations that cause the UI interface to stop responding, thereby reducing the user's experience. So, to avoid the UI thread losing its response, Android recommends , However, new threads may also need to dynamically update the UI components: for example, you need to get a Web page from the Internet, and then display its source code in TextView, you should connect to the network, get the operation of network data () is done in the new thread. However, the problem is: How do we update the UI component data after getting the network data, because the new thread does not allow the UI component to be updated directly ? To solve the problem of updating UI components by new threads, Android offers several solutions: (1) Use the handler messaging mechanism for communication between threads (as described in the previous article);(2) activity.runonuithread (Runnable);(3) view.post (Runnable);(4) view.postdelayed (Runnable long);(5) asynchronous task. And because the (2) ~ (4) approach has the potential to lead to programming a bit cumbersome, asynchronous tasks can simplify this operation. ii. introduction of AsynctaskThe Android Class Asynctask wraps the inter-thread communication , providing a simple programmatic way for the background thread to communicate with the UI thread: The background thread executes the asynchronous task and notifies the UI of the resultof the operation. You can complete asynchronous operations and refresh the user interface by eliminating the need for child threads and handler. 1.AsyncTask classAsynctask<> is an abstract class that is typically used for inheritance and requires the following three generic parameters to be specified when inheriting asynctask:(1) Params: The type of input parameter that initiates the task execution;(2) Progress: The type of progress value (percentage) of background task completion;(3) Result: the type of the result returned after the background execution of the task, such as String, Integer; main methods in the 2.Async class (1) onpreexecute (): This method will be called by the UI thread before performing the actual background operation . You can do some preparatory work in the method, such as displaying a progress bar on the interface, or instantiating some controls, and this method can be used without implementation. -----(UI thread call, background thread not started, initial chemical work) (2) doinbackground (params...values): executes immediately after the OnPreExecute method executes , and the method runs in the background thread . This will be primarily responsible for performing the more time-consuming background processing work. You can call the Publishprogress () method to update the task progress in real time . The method is an abstract method that the subclass must implement. -----(background thread call, performing background tasks)
(3) onprogressupdate (progress...values): After the Publishprogress method is called, theUI thread This method will be called to show the progress of the task on the interface, for example, by displaying it through a progress bar. -----(UI thread invoke, show background task progress)
(4) OnPostExecute (Result): After Doinbackground execution is complete, the OnPostExecute method is called by the UI thread , and the results of the background calculation ( The Doinbackground method return value ) is passed through the method to the UI thread and displayed to the user on the interface. -----(UI thread call, show background thread run result) (5) oncancelled (): Called when the user cancels the thread operation. Called when oncancelled () is called in the main thread. -----(UI thread call, canceling background thread) iii. Asynchronous task processing development steps1. Create a subclass of Asynctask and specify a type for three generic parameters. If a generic parameter does not require a specified type, it is specified as void. 2. Asynctask The above V method as required;3. Invoke Execute (params ... params) of the instance of the Asynctask subclass to begin the time-consuming task. In addition, the following guidelines are required to use the Asynctask class : (1) The instance of the task must be created in the UI thread ; (2) Execute (Params ...) Method must be called in the UI thread ; (3) do not call manually onpreexecute (), OnPostExecute (Result), Doinbackground ( Params ...), Onprogressupdate (Progress ...) These methods need to be in ui thread (4) The task can only be executed once, and the exception will occur If the number of calls is repeated . Four, the source of actual combat 1. Implement the function 2. Source Code Implementation (1) Mainactivity.javafunction: To get the interface component, instantiate a Asynctask subclass object and call its Exeute (Integer....params) method to specify the parameter params to run a task.
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);//Gets a Downloadtest object and passes the Component object parameters Downbtn.setoncl   Icklistener (New Onclicklistener () {@Override public void OnClick (View v) {Download.execute (200);           }        }); }}
(2) Downloadtest.javafunction: A subclass inherited from Asynctask, where OnPreExecute () is used to perform initialization work for the running background thread (child thread), Doinbackground method runs a background thread, Onprogressupdate method update Ui;o The Npostexecute method handles the results of a background thread run.
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;//With parameter construction method Downloadtest (  TextView Text,progressbar bar) {this.tv = text; THIS.PB = bar; }//without parameter construction method Downloadtest () {}/*1.onpreexecute method * To run initialization related content for child threads (background) */protected void OnPreExecute () {Tv.setvis Ibility (view.visible); Sets the display text component pb.setvisibility (view.visible); Set Display progress bar Super.onpreexecute (); The/*2.doinbackground method * runs a background thread that implements every arg0[0] milliseconds to call the Onprogressupdate method */protected String doinbackground (Integer ... arg0) {for (int i=0;i<100;i++) {publishprogress (i);//Call onprogressupdate method and pass parameter I try {thread.sleep (arg0[0]);   Accumulate once, thread sleeps argo[0] milliseconds} catch (Interruptedexception e) {e.printstacktrace (); }} return "Download Complete"; After the table thread finishes running, the returned value}/*3.ONPRogressupdate method * Calls Publishprogress (i) When the method is called and passes the parameter I to the formal parameter values[0]*/@Override protected void Onprogressupdate (Integer  . Values) {pb.setprogress (values[0]);//Set progress bar value Tv.settext ("downloaded" +values[0]+ "%");//Text component display prompt information Super.onprogressupdate (values); /*4.onpostexecute * * */protected void OnPostExecute (String result) {pb.setvisibility (view.invisible) for processing the background thread  /Hide Progress bar tv.setvisibility (view.visible);//Display UI text display box component Tv.settext (result);  Tv.settextsize (20);  Tv.settextcolor (color.red); Super.onpostexecute (result); }}


Effect Demo:

Source Analysis:through the source code we can know that the main thread by invoking the Asynctask subclass of the Execute () method, and then call the Asynctask subclass of the OnPreExecute method, used to run the background thread before the relevant content for its initialization. The Doinbackground () method is then called in the newly created child thread to implement the background threading functionality and to update the UI content through the Publishprogress () method call Onprogressupdate () method. Finally, the OnPostExecute method is executed in the main line to handle the results of running the background thread. Note: Only the doinbackground () method, and the Publishprogress () method are executed in the child thread , and the other methods are the main thread is executed, so you can update the interface components in these methods.

Android Note 26. Android Asynchronous task processing (asynctask)

Related Article

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.