Android's--asynctask essay

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/46945263

The principle of a single-threaded model must be adhered to when developing Android apps: Android UI operations are not thread-safe and must be executed in the UI thread. There are always two rules to remember in a single-threaded model:

1. Do not block the UI thread
2. Ensure that the Android UI Toolkit is accessible only in the UI thread
When a program starts for the first time, Android initiates a corresponding main thread, which is primarily responsible for handling UI-related events such as user keystroke events, user-touching screen events, and screen drawing events, and distributing related events to the corresponding components for processing. So the main thread is often called the UI thread.
For example, from the Internet to obtain a Web page, in a TextView its source code display, this involves the network operation of the program is generally required to open a thread to complete network access, but after obtaining the page source code, is not directly in the network operation thread Call Textview.settext () Because the main UI thread member cannot be accessed directly from other threads.

Android provides several ways to access the UI thread in other threads.

These classes or methods will also make your code complex and difficult to understand. However, this can get worse when you need to implement some very complex operations and need to update the UI frequently.
To solve this problem, Android 1.5 provides a tool class: Asynctask, which makes it easier to create long-running tasks that need to interact with the user interface. Relatively asynctask is more lightweight and is suitable for simple asynchronous processing without the need for threading and handler.
Asynctask is an abstract class. Asynctask defines three generic type params,progress and result.
The Params is the input parameter that initiates the task execution, such as the URL of the HTTP request.
Progress the percentage of background task execution.
Result background performs the final return of the task, such as String.
The execution of Asynctask is divided into four steps, each of which corresponds to a callback method that should not be called by the application, and what developers need to do is implement these methods.
1) Sub-class Asynctask
2) Implement one or more of the following methods defined in Asynctask
OnPreExecute (), the method is called by the UI thread before performing the actual background operation. You can do some preparatory work in this method, such as displaying a progress bar on the interface.
Doinbackground (Params ...), which executes immediately after the OnPreExecute method executes, runs in the background thread. This will be primarily responsible for performing time-consuming background computations. You can call the Publishprogress method to update the real-time task progress. The method is an abstract method that the subclass must implement.
Onprogressupdate (Progress ...), after the Publishprogress method is called, the UI thread will invoke this method to show the progress of the task on the interface, for example, by displaying it through a progress bar.
OnPostExecute (Result), after Doinbackground execution completes, the OnPostExecute method is called by the UI thread, and the results of the background are passed through the method to the UI thread.
To properly use the Asynctask class, here are a few guidelines to follow:
1) The instance of the task must be created in the UI thread
2) The Execute method must be called in the UI thread
3) do not manually call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods
4) The task can only be executed once, otherwise an exception will occur when multiple calls are made
The parameters of the Doinbackground method and OnPostExecute must correspond, both of which are specified in the generic parameter list of the Asynctask declaration, the first is the Doinbackground accepted parameter, the second is the parameter that shows the progress, The third one is the Doinbackground return and the OnPostExecute passed in parameters.

Get a Web page from the Web and display its source code in a TextView

Package Test.list;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import java.util.ArrayList; Import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import org.apache.http.client.HttpClient; Import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Android.app.activity;import Android.app.progressdialog;import Android.content.context;import Android.content.dialoginterface;import Android.os.asynctask;import Android.os.bundle;import Android.os.Handler; Import Android.os.message;import android.view.view;import android.widget.button;import android.widget.EditText; Import android.widget.textview;/** * Get a Web page from the Web and display its source code in a TextView * @author Liuyazhuang */public class    Networkactivity extends activity{private TextView message;    Private Button Open;    Private EditText URL;       @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.network);       Message= (TextView) Findviewbyid (r.id.message);       Url= (EditText) Findviewbyid (R.id.url);       Open= (Button) Findviewbyid (R.id.open);           Open.setonclicklistener (New View.onclicklistener () {public void OnClick (View arg0) {connect ();    }       });        private void Connect () {pagetask task = new Pagetask (this);    Task.execute (Url.gettext (). toString ()); } class Pagetask extends Asynctask<string, Integer, string> {//variable length input parameter, corresponding to Asynctask.exucute () Pr        Ogressdialog Pdialog;               Public Pagetask (Context context) {Pdialog = new ProgressDialog (context, 0); Pdialog.setbutton ("Cancel", new Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface dialog             , int i) {dialog.cancel ();            }            }); Pdialog.setoncancellistener (New Dialoginterface.oncancellistener () {public void OnCancel (dialoginterfaceDialog) {Finish ();            }            });            Pdialog.setcancelable (TRUE);            Pdialog.setmax (100);            Pdialog.setprogressstyle (progressdialog.style_horizontal);        Pdialog.show (); } @Override protected String Doinbackground (String ... params) {try{HttpClient CLI               ent = new Defaulthttpclient ();               Params[0] represents the URL of the connection httpget get = new HttpGet (params[0]);               HttpResponse response = Client.execute (get);               httpentity entity = response.getentity ();               Long length = Entity.getcontentlength ();               InputStream is = Entity.getcontent ();               String s = null;                   if (is = null) {Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();                   byte[] buf = new byte[128];                   int ch =-1;                   int count = 0; while ((ch = is.read (BUF))! =-1) {                      Baos.write (buf, 0, ch);                      Count + = ch; if (length > 0) {//If you know the length of the response, call publishprogress () Update Progress publishprogress                      ((int) ((Count/(float) length) * 100));                   }//Let thread hibernate 100ms thread.sleep (100);              } s = new String (Baos.tobytearray ());            }//Return the result return s;            } catch (Exception e) {e.printstacktrace ();        } return null;        } @Override protected void oncancelled () {super.oncancelled (); } @Override protected void OnPostExecute (String result) {//returns the contents of the HTML page Message.sette            XT (Result);         Pdialog.dismiss (); } @Override protected void OnPreExecute () {//task start, you can display a dialog box here, which is simple to handle Message.setteXT (r.string.task_started); } @Override protected void Onprogressupdate (Integer ... values) {//Update progress System.out.              println ("+values[0");              Message.settext ("+values[0");        Pdialog.setprogress (Values[0]); }     }}

Finally, it needs to be explained that Asynctask cannot completely replace threads, and logic that is more complex or needs to be executed repeatedly in the background may require threads to be implemented.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android's--asynctask essay

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.