Android basics 02 -- thread security 5: asynctask

Source: Internet
Author: User

Android UI operations are not thread-safe, and only the main thread can operate the UI. At the same time, the main thread has a certain time limit on UI operations (up to 5 seconds ). To perform some time-consuming operations (such as downloading and opening large files), Android provides some column mechanisms. The articles in the "android basics 02-thread security" series refer to a series of articles compiled by many online users and introduce the main methods. They are as follows:

Android basics 02 -- thread security 1: Definitions and Examples

Android basics 02 -- thread security 2: handler, message, and runnable

Android basics 02 -- thread security 3: Message, messagequeue, handler, Logoff

Android basics 02 -- thread security 4: handlerthread

Android basics 02 -- thread security 5: asynctask

In thread security, subthreads are used for processing to operate the UI of the main thread. In Android development, you can also use the following two methods:

Handlerthread
Asynctask

This topic describes asynctask.

When developing Android applications, you must follow the single-thread model principle: Android UI operations are not thread-safe and must be executed in the UI thread. In a single-threaded model, you must always remember the following two rules:
1. Do not block the UI thread
2. Make sure to only access the android UI toolkit in the UI thread
When a program is started for the first time, Android starts a corresponding main thread at the same time. The main thread is mainly responsible for processing UI-related events, such as user key events, the user contacts screen events and Screen Drawing events, and distributes related events to corresponding components for processing. Therefore, the main thread is often called the UI thread.
For example, you can obtain a webpage from the Internet and display its source code in a textview. This kind of program involving network operations generally requires a thread to complete network access. However, after obtaining the page source code, yes. textview cannot be called directly in the Network Operation thread. settext. because other threads cannot directly access the main UI thread members.
Android provides several methods to access the UI thread in other threads.
Activity. runonuithread (runnable)
View. Post (runnable)
View. postdelayed (runnable, long)
Hanlder
These classes or methods also make your code complex and hard to understand. However, when you need to implement complex operations and frequently update the UI, this will become worse.
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 speaking, asynctask is more lightweight and suitable for simple asynchronous processing. It can be implemented without the use of threads and handler.
Asynctask is an abstract class. asynctask defines three generic types: Params, SS, and result.
Input parameters for Params startup task execution, such as the URL of the HTTP request.
Percentage of progress background tasks.
Result: The result returned when the task is executed in the background, such as string.
The execution of asynctask is divided into four steps. Each step corresponds to a callback method, which should not be called by the application. All developers need to do is implement these methods.
1) subclass asynctask
2) implement one or more of the following methods defined in asynctask
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.
Doinbackground (Params...) will be executed immediately after the onpreexecute method is executed. This method runs in the background thread. Here, we will primarily perform those time-consuming background computing tasks. You can call publishprogress to update the real-time task progress. This method is an abstract method and must be implemented by sub-classes.
Onprogressupdate (Progress...), after the publishprogress method is called, UI thread will call this method to display the progress of the task on the interface, for example, display through a progress bar.
Onpostexecute (result). After doinbackground is executed, the onpostexecute method will be called by the UI thread, and the background computing result will be passed to the UI thread through this method.
To correctly use the asynctask class, the following guidelines must be followed:
1) The task instance must be created in the UI thread.
2) The execute method must be called in the UI thread.
3) do not manually call the onpreexecute (), onpostexecute (result), doinbackground (Params...), onprogressupdate (Progress...) methods.
4) The task can only be executed once. Otherwise, exceptions may occur during multiple calls.
The doinbackground method and the onpostexecute parameter must correspond to each other. These two parameters are specified in the generic parameter list declared by asynctask. The first parameter is the parameter accepted by doinbackground, and the second parameter is the parameter indicating the progress, the third parameter is the doinbackground return and the parameter passed in onpostexecute.

It should be noted that asynctask cannot completely replace the thread. In some logic that is complicated or needs to be executed repeatedly in the background, it may need to be implemented by the thread.
Obtain a webpage from the Internet 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. conte NT. 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; public class networkactivity extends activity {private textview message; private button open; private edittext URL; @ override pub LIC 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 Paget Ask (this); task.exe cute (URL. gettext (). tostring ();} class pagetask extends asynctask <string, integer, string> {// variable length input parameter, with asynctask. exucute () corresponds to progressdialog pdialog; Public pagetask (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 (dialoginterface DIALOG) {finish () ;}}); pdialog. setcancelable (true); pdialog. setmax (100); pdialog. setprogressstyle (progressdialog. style_horizontal); pdialog. show () ;}@ override protected string doinbackground (string... params) {try {httpclient client = new defaulthttpclient (); // Params [0] indicates the URL of the connection httpget get = ne W httpget (Params [0]); httpresponse response = client.exe cute (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 response length, call publishprogress () to update the publishprogress (INT) (count/(float) length) * 100);} // sleep the thread for 100 ms thread. sleep (100);} s = new string (baos. tobytearray ();} // return s;} catch (exception e) {e. printstacktrace ();} return NULL;} @ override protected void oncancelled () {super. oncancelled () ;}@ override protected void onpostexecute (string result) {// return the message of the HTML page. settext (result); pdialog. dismiss () ;}@ override protected void onpreexecute () {// start the task. A dialog box is displayed here, where message is processed. 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]) ;}}

After reading the source code of asynctask, you will see the following statement in the file header. In this statement, you can easily understand how to use asynctask:

/** * <p>AsyncTask enables proper and easy use of the UI thread. This class allows to * perform background operations and publish results on the UI thread without * having to manipulate threads and/or handlers.</p> * * <p>An asynchronous task is defined by a computation that runs on a background thread and * whose result is published on the UI thread. An asynchronous task is defined by 3 generic * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, * and 4 steps, called <code>begin</code>, <code>doInBackground</code>, * <code>processProgress</code> and <code>end</code>.</p> * * 

Unfinished, to be continued

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.