I want to use an AsyncTask in my app, but I am having trouble finding a code snippet with a simple explanation of how things work. I just want something to help me get back up to speed quickly without having to wade through the documentation or lots of Q&As again.
            Asked
            
        
        
            Active
            
        
            Viewed 5.1k times
        
    47
            
            
         
    
    
        Peter Mortensen
        
- 30,738
- 21
- 105
- 131
 
    
    
        Suragch
        
- 484,302
- 314
- 1,365
- 1,393
- 
                    3What is wrong with http://developer.android.com/reference/android/os/AsyncTask.html – Selvin Sep 03 '14 at 15:17
- 
                    2also [Using AsyncTask](http://stackoverflow.com/questions/18898039/using-asynctask/18898105#18898105) – codeMagic Sep 03 '14 at 15:18
- 
                    2It was actually better in it's original form. Now, it looks too broad for SO. Your wanting to share and help is appreciated. [But even self-answer questions should adhere to SO guidelines](http://meta.stackoverflow.com/questions/261616/self-answer-questions-being-too-broad). The original Q&A was good just a dupe and there is nothing wrong with that. [See this meta post](http://meta.stackoverflow.com/questions/265736/should-i-delete-my-question-if-it-is-marked-as-a-duplicate) – codeMagic Sep 06 '14 at 14:41
1 Answers
226
            AsyncTask is one of the easiest ways to implement parallelism in Android without having to deal with more complex methods like Threads. Though it offers a basic level of parallelism with the UI thread, it should not be used for longer operations (of, say, not more than 2 seconds). 
AsyncTask has four methods
- onPreExecute()
- doInBackground()
- onProgressUpdate()
- onPostExecute()
where doInBackground() is the most important as it is where background computations are performed.
Code:
Here is a skeletal code outline with explanations:
public class AsyncTaskTestActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);  
        // This starts the AsyncTask
        // Doesn't need to be in onCreate()
        new MyTask().execute("my string parameter");
    }
    // Here is the AsyncTask class:
    //
    // AsyncTask<Params, Progress, Result>.
    //    Params – the type (Object/primitive) you pass to the AsyncTask from .execute() 
    //    Progress – the type that gets passed to onProgressUpdate()
    //    Result – the type returns from doInBackground()
    // Any of them can be String, Integer, Void, etc. 
    private class MyTask extends AsyncTask<String, Integer, String> {
        // Runs in UI before background thread is called
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Do something like display a progress bar
        }
        // This is run in a background thread
        @Override
        protected String doInBackground(String... params) {
            // get the string from params, which is an array
            String myString = params[0];
            // Do something that takes a long time, for example:
            for (int i = 0; i <= 100; i++) {
                // Do things
                // Call this to update your progress
                publishProgress(i);
            }
            return "this string is passed to onPostExecute";
        }
        // This is called from background thread but runs in UI
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            // Do things like update the progress bar
        }
        // This runs in UI when background thread finishes
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Do things like hide the progress bar or change a TextView
        }
    }
}
Flow Diagram:
Here is a diagram to help explain where all the parameters and types are going:
Other helpful links:
- What arguments are passed into AsyncTask<arg1, arg2, arg3>?
- Slidenerd Android AsyncTask Tutorial: Android Tutorial For Beginners
- Understanding AsyncTask – Once and Forever
- Dealing with AsyncTask and Screen Orientation
- How to pass multiple parameters to AsynkTask
- how to pass in two different data types to AsyncTask, Android
 
    
    
        Suragch
        
- 484,302
- 314
- 1,365
- 1,393
- 
                    very cool man, the documentation as usually is not there I've been using without really knowing why I had do it that way. – becker Sep 16 '17 at 19:06
- 
                    2Visualizing the data flow to constructor will make the image more beautiful! – Mohammed H Jan 19 '18 at 06:08
