Android asynchronous task AsyncTask

Source: Internet
Author: User

Android asynchronous task AsyncTask

AsyncTask

AsyncTask is mainly used to update UI threads. Time-consuming operations can be used in AsyncTask.

AsyncTask is an abstract class that must be inherited during use and then the execute () method is called. Note that three generic Params, SS, and Result types must be set during inheritance, such as AsyncTask. :

    Params refers to the same type of parameters passed in when the execute () method is called as the doInBackgound () parameter type. Progress refers to the parameter type passed during update, that is, publishProgress () like the parameter type of onProgressUpdate (), Result indicates the return value type of doInBackground (). The preceding description involves several methods:
    • The doInBackgound () method is required to inherit from AsyncTask and runs in the background. Time-consuming operations can be done here.
    • PublishProgress () Update Progress, and pass the progress parameter to onProgressUpdate () (in the UI main process, execute this method)
    • OnProgressUpdate () is called after publishProgress () call, Update Progress

      Three types of asynchronous tasks are used:

      1. Params , The type parameter sent to the task for execution.
      2. The Type Unit of Progress in Progress is published in background computing.
      3. Result indicates the type calculation of the background Result.






        Use AsyncTask in the following three steps:

        1. Create an AsyncTask class and specify the type for the three generic parameters. If a generic parameter does not need to specify a type, it can be specified as void

        <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + signature + MqGiuPm + 3dDo0qrKtc/Signature + CjxjZW50ZXI + signature/Signature + signature + CjxjZW50ZXI + signature/Signature + signature + pipeline + CjxjZW50ZXI + pipeline/pipeline + PC9jZW50ZXI + CjxjZW50ZXI + pipeline/pipeline + Pipeline "" alt = "\">

        Package com. example. asynctestdemo; import java. io. byteArrayOutputStream; import java. io. IOException; import java. io. inputStream; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. httpStatus; import org. apache. http. client. clientProtocolException; 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. OS. asyncTask; 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 bt_execute; private Button bt_cancel; private ProgressBar progressBar; private TextView textView; MyTask myTask; protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); bt_execute = (Button) findViewById (R. id. bt_execute); bt_cancel = (Button) findViewById (R. id. bt_cancel); progressBar = (ProgressBar) findViewById (R. id. progressBar); textView = (TextView) findViewById (R. id. text_view); bt_execute.setOnClickListener (new OnClickListener () {public void onClick (View v) {// instantiate the asynchronous task MyTask class myTask = new MyTask();myTask.exe cute ("http://www.baidu.com ");}}); bt_cancel.setOnClickListener (new OnClickListener () {public void onClick (View v) {myTask. cancel (true) ;}});} class MyTask extends AsyncTask
              
               
        {// The onpreExecute () method is used to perform some UI operations protected void onPreExecute () {textView before running background tasks. setText ("Loading ...... ");} // doInBackground () method, which internally executes time-consuming tasks in the background, but does not allow you to modify UIprotected String doInBackground (String... params) {try {HttpClient client = new DefaultHttpClient (); HttpGet get = new HttpGet (params [0]); HttpResponse response = client.exe cute (get); if (response. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {HttpEntity entity = response. getEntity (); InputStream is = entity. getContent (); long total = entity. getContentLength (); System. out. println (total); ByteArrayOutputStream baos = new ByteArrayOutputStream (); byte [] buf = new byte [1024]; int count = 0; int length =-1; while (length = is. read (buf ))! =-1) {baos. write (buf, 0, length); count + = length; // call the publishProgress () method to publish the progress, and the onProgressUpdata method will be executed publishProgress (int) (count/length); // pause 0.5sThread.sleep (500);} return new String (baos. toByteArray (), "UTF-8") ;}} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} catch (InterruptedException e) {e. printStackTrace ();} return null;} // onProgressUpdata method, used to update progress information, such as executing the progress bar program protected void onProgressUpdate (Integer... values) {progressBar. setProgress (values [0]); textView. setText ("Loading ...... "+ values [0]);} // onPostExecute method, used to update the UI after the background task is executed. The displayed result is protected void onPostExecute (String result) {textView. setText (result);} // onCacelled method, used to change UIprotected void onCancelled () {textView when canceling a task in progress. setText ("canceled"); progressBar. setProgress (0 );}}}
              




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.