The Asynctask of Android learning

Source: Internet
Author: User

As we have already mentioned in the handler messaging mechanism for Android Learning (http://www.cnblogs.com/zhouhb/p/5812447.html), Android only allows the UI thread to modify the UI components in the activity. This causes the newly started thread to not dynamically change the property values of the interface component. In order to solve the problem that the new thread cannot update the UI component, you can use Asyctask in addition to the handler messaging mechanism. 1 Asynctask Introduction to How to use Asynctask<params, Progress, Result> is an abstract class that is typically used for inheritance. Inheriting asynctask requires specifying the following three generic parameters:
    • Params: This generic specifies the type of arguments we pass to the asynchronous task when it executes
    • Progress: This generic specifies the type of parameters that our asynchronous task will execute when it executes the progress returned to the UI thread
    • Result: The type of results returned to the UI thread after this generic specified asynchronous task finishes executing
When we define a class that inherits the Asynctask class, we must specify the three generic types, and if none are specified, write them void, for example: Asynctask <void, void, void> when we perform an asynchronous task, It needs to be performed in the following 4 steps, respectively
    • OnPreExecute (): This method is executed before the asynchronous task is executed, usually in this method we do some initialization of the UI controls, such as the popup progress bar.
    • Doinbackground (params ... params): This method is the method used to handle asynchronous tasks . The method can call the Publishprogress (Progress) method to update the execution progress of the task.
    • Onprogressupdate (Progess ... values): Calling the Publishprogress (Progress) method in the Doinbackground method triggers the method.
    • OnPostExecute (Result): When the Doinbackground (params) method completes, the system automatically calls the method and Doinbackground (params ... Params) method is passed to the method by the return value of the
Principles to be followed when using Asynctask: (1) An instance of Asynctask must be created in the UI thread, and (2) must be in the UI threadCall the Execute () method of Asynctask; (3) Asynctask OnPreExecute (), doinbackground (params ... params), onprogressupdate (progess ... values), and the OnPostExecute (Result ... result) method should not be called by the programmer code, but is called by the system, (4) Each asynctask can only be executed once, and multiple calls will throw an exception. 2 Asynctask Use instance 2.1 activity code
public class Mainactivity extends Activity {private TextView show;private Button btn; @Overrideprotected void OnCreate (Bun Dle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); show= ( TextView) Findviewbyid (r.id.show); Show.setmovementmethod (Scrollingmovementmethod.getinstance ()); btn= (Button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO Auto-generated method Stubdotask ();}});} private void Dotask () {//TODO auto-generated method Stubdowntask task=new downtask (this,show); try {task.execute (new URL ( "http://www.szit.edu.cn/"));} catch (Malformedurlexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}

  

Subclass Downtask Code for 2.2 Asynctask
public class Downtask extends Asynctask<url, Integer, String>{progressdialog progressdialog;int hasread=0; Context context; TextView show;public downtask (Context context,textview show) {this.context=context;this.show=show;} @Overrideprotected String doinbackground (URL ... arg0) {//TODO auto-generated method Stubstringbuilder sb=new StringBuilder (); try {urlconnection conn=arg0[0].openconnection (); BufferedReader br=new BufferedReader (New InputStreamReader (Conn.getinputstream (), "gb2312")); String line= "", while ((Line=br.readline ())!=null) {sb.append (line+ "\ n"), hasread++;p ublishprogress (Hasread);}} catch (Exception e) {//Todo:handle Exception}return sb.tostring ();} @Overrideprotected void OnPostExecute (String result) {//TODO auto-generated method Stubshow.settext (Result); Progressdialog.dismiss ();} @Overrideprotected void OnPreExecute () {//TODO auto-generated Method Stubprogressdialog=new ProgressDialog (context); Progressdialog.settitle ("in Task Execution");p rogressdialog.setmessage ("Please Wait");p ROGRESSDIalog.setcancelable (False);p Rogressdialog.setmax;p Rogressdialog.setprogressstyle (progressdialog.style_ Horizontal);p Rogressdialog.setindeterminate (False);p rogressdialog.show ();} @Overrideprotected void Onprogressupdate (Integer ... values) {//TODO auto-generated method Stubshow.settext ("read" + values[0]+ "line");p rogressdialog.setprogress (Values[0]);}}

  

Other examples of use of asynctask can be further referenced in Android multi-threaded-----asynctask (http://www.cnblogs.com/xiaoluo501395377/p/3430542.html).

The Asynctask of Android learning

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.