Last Updated: January 19, 2015

AsyncTask Android Example

Introduction

Asynctask(Asynchronous task) in android enable us to perform the task in Background thread giving us the way to separate our tedious work from UI Thread and publish our work back to UI thread after our work get completed.




It has following method(listed in sequence of execution):
    • onPreExceute
    • doInBackGround
    • publishProgress
    • onProgressUpdate
    • onPostExceute
    Note:  We can't access any android widgets (button, progressDialog etc.) elements in       doInBackground. So for updating our work status we publish the progress from doInBackground.

    Android ExampleAsynctask<Params,Progress,Result>


    class AsyncTaskExample extends AsyncTask<Void, Integer, String> {
        
        private  final String TAG = AsyncTaskExample.class.getName();
        
        protected void onPreExecute(){
            Log.d(TAG, "On preExceute...");
        }
        
        protected String doInBackground(Void...arg0) {
            
            Log.d(TAG, "On doInBackground...");
            
            for(int i = 0; i<5; i++){
                Integer in = new Integer(i);
                publishProgress(i);
            }
            
            return "You are at PostExecute";}
        
        protected void onProgressUpdate(Integer...a){
            Log.d(TAG,"You are in progress update ... " + a[0]);
        }
        
        protected void onPostExecute(String result) {
            Log.d(TAG,result); 
        }
    }



    Call in your activity(Any):

     new AsyncTaskExample().execute() - In Our example
     new AsyncTaskExample().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); - for serial task execute.  
     new AsyncTaskExample().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)- For Parallel task.  
    

    Output:









    0 comments :

    Post a Comment

    Your comments are valuable for us !!!