Search code examples
javaandroidandroid-asynctask

Android: how does the execute() method in AsyncTask work?


So I am currently learning about AsyncTask in Android and there is the following simple example:

public class MainActivity extends AppCompatActivity {

    public class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {

            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(urls[0]);
            ...
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DownloadTask task = new DownloadTask();
        String result = null;
        try {
            result = task.execute("http://someURL").get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.i("Result",result);
    }
}

The only thing I don't understand about the example is the following:

In the try section there is a string being passed to the execute method. The execute method is part of the task object. The doInBackground method is also part of the task object. How does the doInBackground method know about the content that I am passing to the execute method? Because in the tutorial I learned, that the url = new URL(urls[0]); contains the info of the string that is passed through the execute method. Can someone explain this connection to me?


Solution

  • The class DownloadTask is a direct child class of AsyncTask. AsyncTask provides an implementation to manage a task in async way and you don't need to worry about any details about thread pool or any other details. AsyncTask class uses Java generics, i.e. a template with three parameters. You are using String as first and third parameter of the template, so it means doInBackground will take a variant number of String objects and it will return a String object. The "connection" between execute method and doInBackground is inside AsyncTask class and it's hidden in the parent class, it's the encapsulation and information hiding usually performed in object oriented design.

    public class DownloadTask extends AsyncTask<String, Void, String> {
    
            @Override
            protected String doInBackground(String... urls) {
    
                URL url;
                HttpURLConnection urlConnection = null;
    
                try {
                    url = new URL(urls[0]);
                ...
            }
        }