android--Asynchronous Task Asynctask

Source: Internet
Author: User


Example: Using an asynchronous task to download from the network


package com.example.xiaocool.anysctaskdemo;import android.app.progressdialog;import  android.content.context;import android.os.asynctask;import android.os.bundle;import  android.support.v7.app.actionbaractivity;import android.view.view;import android.widget.button; import android.widget.textview;import java.io.bufferedreader;import java.io.inputstreamreader; Import java.net.malformedurlexception;import java.net.uri;import java.net.urlconnection;public  class MainActivity extends ActionBarActivity {    private  textview show;    private button download;     @Override     protected void oncreate (bundle savedinstancestate)  {         super.oncreate (savedinstancestate);         setcontentview (r.layout.activity_Main);        show =  (TextView)  this.findviewbyid ( R.id.show_down);        download =  (Button)   This.findviewbyid (R.id.button);         download.setonclicklistener (new  view.onclicklistener ()  {            @ Override            public void onclick ( VIEW&NBSP;V)  {                 downtask task = new downtask (mainactivity.this);                 try {                     /**                      *  starts to perform time-consuming tasks                       */                      task.execute (New uri ("http://news.baidu.com/"));                 } catch  (exception e)  {                      E.printstacktrace ();                 }            }         });    }    /**     *  params   Start Task executionThe type of input parameter      * Progress  the progress of the background task completion is worth the type,     *  result    after the background execution task finishes   returns the type of the result      *  if you do not need to specify a type  Void      * <p/>     *  overridden methods have system calls       */    class downtask extends asynctask<uri, integer,  String> {        ProgressDialog progressDialog;         //defines the number of read rows that are recorded          int hasread = 0;        context mcontext;         public downtask (Context context)  {             mContext = context;         }        /**         *  The task that the background thread is about to complete, which can call Publishprogress (progress value) to update the execution progress of the task           *         *  @param  params          *  @return          */          @Override          Protected string doinbackground (Uri... params)  {             stringbuilder sb = new stringbuilder ();             try {                 urlconnection conn = params[0].tourl (). OpenConnection ();   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//Open conn Connection corresponding input stream, packaged into Bufferreader   Objects                  Bufferedreader br = new bufferedreader (                         new  InputStreamReader (Conn.getinputstream (),  "Utf-8")                  );                 String line = null;                 while  ((Line = br.readline ())  !=  null)  {                     sb.appEnd (line +  "\ n");                     hasRead++;                     //Update task Execution Progress                      publishprogress ( Hasread);                 }                 return  Sb.tostring ();            } catch  ( Exception e)  {                 e.printstacktrace ();             }             return null;        }         /**         *  Called Publishprogress (Progress value) in the Doinbackground method, the method is triggered after the progress of the task is updated           *         *  @param  values          */         @Override          protected void onprogressupdate (Integer... values)  {            show.settext ("read" +values[0]);             progressdialog.setprogress (Values[0]);         }        /**          *  This method will be called when executing the background time-consuming program, which is used to complete some initialization preparations, such as displaying a progress bar on the interface           */         @Override          protected void onpreexecute ()  {             progressdialog = new progressdialog (Mcontext);             progressdialog.settitle ("The task is executing! ");             progressdialog.setmessage (" The task is executing, Later!! ");             //Cancel button not available              progressdialog.setcancelable (False);             progressdialog.setmax (202);             progressdialOg.setprogressstyle (progressdialog.style_horizontal);             progressdialog.setindeterminate (False);             progressdialog.show ();        }         /**         *  When the Doinbackground method is complete, the system automatically calls the method   and passes the return value of Doinbackground () to the method           *         *  @param  s          */         @Override          protected void onpostexecute (string s)  {             //back to html  page content              show. SetText (s);             progressdialog.dismiss ();         }    }}


android--Asynchronous Task Asynctask

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.