Thursday, January 22, 2015

ASYNCTASK

AsyncTask class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. Complexity involved in creating thread to do background operation and updating main UI thread been resoved in AsyncTask. 
AsyncTask must be subclassed to use. 

private class MyTask extends AsyncTask < Params, Progress, Result >

An asynchronous task is defined by 3 generic types, called 
ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate andonPostExecute. 
public class AsyncTest extends Activity {
    private TextView _percentField;
        private Button _cancelButton;
    private MyTask _myTask;
 
    @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);  
 
        //include text and button widgets in main layout.
       _percentField = ( TextView ) findViewById( R.id.percent_field );
       _cancelButton = ( Button ) findViewById( R.id.cancel_button );
       _cancelButton.setOnClickListener( new CancelButtonListener());  
       _myTask = new MyTask();
       _myTask.execute( this );
     }
 
     private class CancelButtonListener implements View.OnClickListener{
 
     public void onClick(View v) {
 
    //onCancelled gets called after this.
    _myTask.cancel(true);
        }
     }
 
private class MyTask extends AsyncTask < Context, Integer, String > {
 
        @Override
        protected String doInBackground(Context... params) {
        Log.i("AsyncTest", "doInBackground()");
                int i = 0;
                while( i <= 50 ){
                    try{
                          Thread.sleep( 50 );
                          //publishes the UI thread: onProgressUpdate gets called
                          publishProgress( i ); 
                          i++;
                          } catch( Exception e ){
                              Log.i("AsyncTest", e.getMessage() );
                              }
                    }
               //return value passes to onPostExecute method
               return "COMPLETE!";
           }
 
        @Override
        protected void onCancelled() {
            Log.i("AsyncTest", "onCancelled()");
            super.onCancelled();
                        _percentField.setText( "Cancelled!" );
                        _percentField.setTextColor( 0xFFFF0000 );
        }       
          
         //onPostExecute method runs in UI thread after doInBackground 
         //method returns
         //@result - return value of doInBackground
        @Override
        protected void onPostExecute(String result) {
            Log.i("AsyncTest", "onPostExecute()");
            super.onPostExecute(result);
                        _percentField.setText( result );
                        _percentField.setTextColor( 0xFF69adea );
                        _cancelButton.setVisibility( View.INVISIBLE );
        }               
 
         //When ever publishProgress method been called inside doInBackground -
         //onProgressUpdate method runs in UI thread(can update UI)
         //@ Integer... values - second parameter in MyTask      
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
                        Log.i( "AsyncTest", "onProgressUpdate(): " +  String.valueOf( values[0] ) );
                        _percentField.setText( ( values[0] * 2 ) + "%");
                        _percentField.setTextSize( values[0] );
        }
    }
 
}

0 comments:

Post a Comment