Android AsyncTask

“AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.” – developer.android

Async task class definition

class AsyncTaskClassName extends AsyncTask<argumentType, progrssValueType, taskResultType> {

     //inputarg can contain array of values
     protected taskResultType doInBackground(argumentType... inputarg) {

         //-------
         //-- Your Long running task here ----

         int count = inputarg.length;

         for (int i = 0; i < count; i++) {
             Log.i("from Async task", inputarg[i] );
         }

         //-------

         publishProgress(progrssValue));


         return taskresult;
     }

     protected void onProgressUpdate(progrssValueType... progress) {

         //update the progress
         setProgressPercent(progress[0]);

     }
     
     //this will call after finishing the doInBackground function
     protected void onPostExecute(taskResultType result) {

         // Update the ui elements 
         //show some notification
         showDialog("Task done "+ result);

     }
 }

starting task

new AsyncTaskClassName().execute(arg1, arg2, etc );

 

Or we can execute directly

new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground(Void... params) {
        //long running task
        return null ;
    }


    @Override
    protected void onPostExecute(Void x) {
        //update the ui elemets
    }
}.execute();

 

 

ref : https://developer.android.com/reference/android/os/AsyncTask.html

Author: bm on July 13, 2016
Category: Android

3 thoughts on “Android AsyncTask

  1. The UI element you are updating might become invalid by the time your onPostExecute() will be called, a better approach will be to pass the weakreference of the view you want to update and check if it is still valid before doing some operation on it.

    Something like this:

    public class MyAsyncTask extends AsyncTask {
    
        private final WeakReference mContextWeakReference;
    
        public MyAsyncTask(Context context){
            mContextWeakReference = new WeakReference(context);
        }
    
        @Override
        protected void onPostExecute(Boolean success) {
            super.onPostExecute(success);
            if(success != null && success){                             
                Context context = mContextWeakReference.get();
                if(context != null) {
                    //update the ui
                }
            }
        }
    

    You can pass the view itself which you would want to update instead of context, say like ProgressBar and store it in weakreference.

Your comment:

Your Name

Comment:




Last articles