Detailes using Android with AsyncTask Part1

Detailes using Android with AsyncTask

Asynchronous task mechanism in Android, there are two ways, Handler and AsyncTask.
Handler mode for each task you need to create a new thread, Handler instance by sending a message to the UI thread, complete interface update task is completed, this way to control the entire process is relatively fine, but there are also disadvantages, such as code opposite bloated, perform multiple tasks at the same time, easy to thread precise control. Handler relevant knowledge on the front has also been introduced, it is unclear friends can refer to it.
To simplify operation, Android1.5 provides tools android.os.AsyncTask, it makes it easier to create asynchronous tasks, no longer need to write task threads and Handler instances to accomplish the same task.
Let's look at the definition AsyncTask of:


public  abstract  class  AsyncTask <Params, Progress, Result> {

Three generic type representing the "input parameter to start the task execution" and "background task execution schedule", "backstage calculation type." In certain cases, not all types are used, if not used, can be replaced with java.lang.Void type.
A perform asynchronous tasks typically include the following steps:
1. execute (Params ... params) , perform an asynchronous task, we need to call this method in your code, trigger the execution of asynchronous tasks.
2. onPreExecute () , immediately after the execute (Params ... params) is called, is generally used to perform background tasks before the UI to make some marks.
3. doInBackground (Params ... params) , in onPreExecute () immediately after the completion of the implementation, for the implementation of a more time-consuming operation, this method will receive input parameters and returns the results. In the process of implementation can call publishProgress (Progress ... values) to update the progress information.
4. onProgressUpdate (Progress ... values) , when calling publishProgress (Progress ... values), this method is executed, it will update the progress information directly to the UI components.
5. onPostExecute (Result result) , when the end of a background operation, this method will be called, the results will be passed as an argument to this method, the direct result is displayed on the UI components.
When in use, there are a few things to pay particular attention to:
Examples 1. asynchronous tasks must be created in the UI thread.
2.execute (Params ... params) method must be called on the UI thread.
3. Do not manually call onPreExecute (), doInBackground (Params ... params), onProgressUpdate (Progress ... values), onPostExecute (Result result) these methods.
4. You can not change the information UI components doInBackground (Params ... params) in.
5. A task instance can only be executed once, if you perform a second time will throw an exception.
Next, we look at how to use AsyncTask perform asynchronous task operation, we first create a project structure is as follows:



The structure is relatively simple, let's look at MainActivity.java code:

Package  com.scott.async; 
Import  java.io.ByteArrayOutputStream; 
Import  java.io.InputStream; 
Import  org.apache.http.HttpEntity; 
Import  org.apache.http.HttpResponse; 
Import  org.apache.http.HttpStatus; 
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.util.Log; 
Import  android.view.View; 
Import  android.widget.Button; 
Import  android.widget.ProgressBar; 
Import  android.widget.TextView; 
public  class  MainActivity  extends  Activity { 
     
    Private  static  Final  String TAG =  "ASYNC_TASK" ; 
     
    Private  Button execute; 
    Private  Button Cancel; 
    Private  ProgressBar progressBar; 
    Private  TextView textView; 
     
    Private  MyTask mTask; 
     
    Override 
    public  void  onCreate (Bundle savedInstanceState) { 
        Super .onCreate (savedInstanceState); 
        setContentView (R.layout.main); 
         
        execute = (Button) findViewById (R.id.execute); 
        execute.setOnClickListener ( new  View.OnClickListener () { 
            Override 
            public  void  onClick (View v) { 
                // Note that each required a new instance, the new task can only be executed once, there would be an exception 
                mTask =  new  MyTask (); 
                mTask.execute ( "http://www.androidx7.com" ); 
                 
                execute.setEnabled ( false );              
                cancel.setEnabled ( true ); 
          
        cancel = (Button) findViewById (R.id.cancel); 
        cancel.setOnClickListener ( new  View.OnClickListener () { 
            Override 
            public  void  onClick (View v) { 
                // Cancel the task being executed, onCancelled method will be called 
                mTask.cancel ( true ); 
      

        progressBar = (ProgressBar) findViewById (R.id.progress_bar); 
        textView = (TextView) findViewById (R.id.text_view); 
         
     
     
    Private  class  MyTask  extends  AsyncTask <String, Integer, String> { 
        // OnPreExecute method for performing background tasks before doing some UI operations 
        Override 
        protected  void  onPreExecute () { 
            Log.i (TAG,  "onPreExecute () Called" ); 
            textView.setText ( "loading ..." ); 
       
         
        Internal // doInBackground method to perform background tasks can not be modified in this method UI 
        Override 
        protected  String doInBackground (String ... params) { 
            Log.i (TAG,  "doInBackground (Params ... params) Called" );  
            try  { 
                HttpClient Client =  new  DefaultHttpClient (); 
                HttpGet get =  new  HttpGet (params [ 0 ]); 
                HttpResponse response = client.execute (get); 
                if  (response.getStatusLine (). getStatusCode () == HttpStatus.SC_OK) { 
                    HttpEntity entity = response.getEntity (); 
                    InputStream is = entity.getContent (); 
                    Long  Total = entity.getContentLength (); 
                    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 publishProgress schedule announced last onProgressUpdate   method will be executed 
                        publishProgress (( int ) ((count / ( float ) Total) *  100 )); 
                        // To demonstrate progress, sleep 500 milliseconds 
                        Thread.sleep ( 500 ); 

                    return  new  String (baos.toByteArray (),  "GB2312" ); 

            }  catch  (Exception e) { 
                Log.e (TAG, e.getMessage ()); 

            return  null ; 

        // OnProgressUpdate method for updating progress information 
        Override 
        protected  void  onProgressUpdate (Integer ... progresses) { 
            Log.i (TAG,  "onProgressUpdate (Progress ... progresses) Called" ); 
            ProgressBar.setProgress (progresses [ 0 ]); 
            textView.setText ( "loading ..."  + progresses [ 0 ] +  "%" ); 
        
         
        // OnPostExecute method is used in the station after the execution task updates UI, display the results 
        Override 
        protected  void  onPostExecute (String result) { 
            Log.i (TAG,  "onPostExecute (Result result) Called" ); 
            textView.setText (result); 
             
            execute.setEnabled ( true ); 
            cancel.setEnabled ( false ); 

         
        // OnCancelled method used to change the UI when you cancel the execution of the task 
        Override 
        protected  void  onCancelled () { 
            Log.i (TAG,  "onCancelled () Called" ); 
            textView.setText ( "canceled" ); 
            ProgressBar.setProgress ( 0 ); 
             
            execute.setEnabled ( true ); 
            cancel.setEnabled ( false ); 




Main.xml layout file code is as follows:

<? XML  Version = "1.0"  encoding = "UTF-8" ?> 
< LinearLayout  xmlns: Android = "http://schemas.android.com/apk/res/android" 
    Android: Orientation = "Vertical" 
    Android: layout_width = "fill_parent" 
    Android: layout_height = "fill_parent" > 
    < Button 
        Android: ID = "@ + ID / execute" 
        Android: layout_width = "fill_parent" 
        Android: layout_height = "wrap_content" 
        Android: text = "execute" /> 
    < Button 
        Android: ID = "@ + ID / Cancel" 
        Android: layout_width = "fill_parent" 
        Android: layout_height = "wrap_content" 
        Android: enabled = "false" 
        Android: text = "Cancel" /> 
    < ProgressBar  
        Android: ID = "@ + ID / progress_bar"  
        Android: layout_width = "fill_parent"  
        Android: layout_height = "wrap_content"  
        Android: Progress = "0" 
        Android: max = "100" 
        style = "Android:? attr / progressBarStyleHorizontal" /> 
    < ScrollView 
        Android: layout_width = "fill_parent"  
        Android: layout_height = "wrap_content" > 
        < TextView 
            Android: ID = "@ + ID / text_view" 
            Android: layout_width = "fill_parent"  
            Android: layout_height = "wrap_content" /> 
    </ ScrollView > 
</ LinearLayout > 


Because of the need to access the network, so we also need to add access to the network in AndroidManifest.xml permissions:

< uses-permission  Android: name = "android.permission.INTERNET" /> 


We look at the interface at runtime:






Several more shots were initial interface, the implementation of asynchronous task interface, the interface after successful execution, cancel the task after the interface. After the successful implementation of the whole process log is printed as follows:

If we press the "cancel" button in carrying out its mandate, the log is printed as follows:







Share this

Related Posts

Previous
Next Post »