Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AsyncTask example and explanation [duplicate]

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.

like image 834
Suragch Avatar asked Sep 03 '14 15:09

Suragch


People also ask

What is AsyncTask in Android with example?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

What is the replacement of AsyncTask?

Alternative 1: Using Executor and Handler The executor will help in performing any task in the background and the handler will help to make UI changes.

How many times an instance of AsyncTask can be executed?

AsyncTask instances can only be used one time.

What happen if we call execute more than once in AsyncTask?

Limitation Of AsyncTask There is a limit of how many tasks can be run simultaneously. Since AsyncTask uses a thread pool executor with max number of worker threads (128) and the delayed tasks queue has fixed size 10. If you try to execute more than 138 AsyncTasks the app will crash with java.


1 Answers

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:

enter image description here

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
like image 118
Suragch Avatar answered Oct 23 '22 09:10

Suragch