Android AsyncTask asynchronous task

Source: Internet
Author: User

Android AsyncTask asynchronous task
I. AsyncTask: (1) Review of relevant knowledge: 1. When developing Android applications, you must follow the single-thread model principle: Android UI operations are not thread-safe, these operations must be executed in the UI thread.
2. 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 control 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.
3. In Versions later than Android, network access is not allowed in the main thread. Generally, programs involving network operations require a new thread to complete network access. However, after obtaining the page data, you cannot return the data to the UI. Because the Worker Thread cannot directly access the members in the UI Thread, that is to say, there is no way to operate the content on the UI interface. If the operation is performed, an exception is thrown: CalledFromWrongThreadException.
In fact, android provides several methods to access the UI thread in other threads:
  • Activity. runOnUiThread (Runnable)
  • View. post (Runnable)
  • View. postDelayed (Runnable, long)
  • Handler message transmission mechanism (explained in subsequent courses) these classes or methods make the code very complex and difficult to understand. In order to solve this problem, Android 1.5 provides a tool class: AsyncTask, which makes it easier to create tasks that interact with the user interface for a long time. AsyncTask is more lightweight and suitable for simple asynchronous processing. It can be implemented without the help of threads and Handler.

    (2) AsyncTask code implementation:
    1. 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. Generally, the String type is used;
    • Percentage of Progress background tasks. Generally, the Integer type is used;
    • Result: The Result returned when a task is executed in the background. Generally, byte [] or String is used.
      2. The execution of AsyncTask is divided into four steps. Each step corresponds to a callback method (the method automatically called by the Application). What developers need to do is to implement these methods.
      1) define the AsyncTask subclass; 2) Implement the methods defined in AsyncTask: (you can implement all or only implement part of them)
      • 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.


        3. Core code:
        @Override        protected void onCreate(Bundle savedInstanceState) {                super.onCreate(savedInstanceState);                setContentView(R.layout.activity_main);                text_main_info = (TextView) findViewById(R.id.text_main_info);                new MyAsyncTask(MainActivity.this).execute(urlString);        }
        Class MyAsyncTask extends AsyncTask
               
                
        {Private Context context; private ProgressDialog pDialog = null; public MyAsyncTask (Context context) {this. context = context; // instantiate a ProgressDialog progress dialog box pDialog = new ProgressDialog (context); pDialog. setIcon (R. drawable. ic_launcher); pDialog. setTitle ("Progress prompt:"); pDialog. setMessage ("loading data ...... "); // The following method is to set a style for the Progress box, if the parameter is 1 or ProgressDialog. STYLE_HORIZONTAL indicates the exact progress bar pDialog. setProgressStyle (ProgressDial Og. STYLE_HORIZONTAL); // Note: when new ProgressDialog () is set, the second parameter is not required. // If the second parameter is 0, the fuzzy progress bar is displayed. If the parameter is 1, the precise progress bar is displayed. If necessary, the Progress value must be calculated.} @ Override protected void onPreExecute () {super. onPreExecute (); pDialog. show (); // display the progress dialog box} @ Override protected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values); // Changes the value in the Progress dialog box. The values parameter is the data continuously returned from the doInBackground () method. PDialog. setProgress (values [0]);} @ Override protected byte [] doInBackground (String... params) {BufferedInputStream bis = null; ByteArrayOutputStream baos = null; HttpURLConnection httpConn = null; // access the network, download data and start try {URL url = new URL (params [0]); httpConn = (HttpURLConnection) url. openConnection (); httpConn. setRequestMethod ("GET"); httpConn. setConnectTimeout (8000); httpConn. setDoInput (true); ht TpConn. connect (); if (httpConn. getResponseCode () == 200) {bis = new BufferedInputStream (httpConn. getInputStream (); baos = new ByteArrayOutputStream (); // The length here represents the length of the entire object int length = httpConn. getContentLength (); // This variable indicates the length of the read data int readLength = 0; byte [] buffer = new byte [256]; int c = 0; while (c = bis. read (buffer ))! =-1) {// readLength + = c, to calculate the total length of readLength + = c as of now; // write the bytes into the memory stream, in the future, it will be easy to install the byte array baos. write (buffer, 0, c); baos. flush (); // The download progress is calculated here. Divide the read length by the total file length. Int progress = (int) (readLength/(float) length * 100); // continuously releases the progress to facilitate onProgressUpdate () method to modify the data publishProgress (progress);} return baos. toByteArray (); // convert the content in the memory stream into a byte array and return the result.} Catch (Exception e) {e. printStackTrace ();} finally {// close the necessary stream and connection to release the resource try {bis. close (); baos. close (); httpConn. disconnect ();} catch (Exception e) {e. printStackTrace () ;}} return null ;}@ Override protected void onPostExecute (byte [] result) {super. onPostExecute (result); if (result! = Null) {// display the downloaded content in the specified text box text_main_info.setText (new String (result);} else {// If the downloaded content is empty, the download fails. If no judgment is made, a null pointer exception occurs. text_main_info.setText ("Download failed! ") ;}// Make the progress dialog box disappear. pDialog. dismiss ();}}
               

        4. 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 onPreExecute (), onPostExecute (Result), doInBackground (Params ...), onProgressUpdate (Progress ...) these methods; 4) The task can only be executed once; otherwise, an exception will occur during multiple calls; The doInBackground method must correspond to the onPostExecute parameter, these two parameters are specified in the generic parameter list declared by AsyncTask. The first parameter is the one 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.

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.