Search code examples
javaandroidandroid-asynctask

How does AsyncTask work one process to another one?


I'm currently studying android on my own and pretty new to java. I'm wondering how AsyncTask works like this: onPreExecute() -> doInBackground() -> onPostExecute(). When I look at others define their AsynTask, it seems like only method is declared in their code with no calls upon the method. I can't figure out how doInBackground() comes after onPreExecute() with no code that links both like:

onPreExecute(){   ~~~~~ call doInBackground()}

My point is that when AsyncTask.execute() is called, onPreExecute() is called, then doInBackground(), finally onPostExecute(). I couldn't find any code in library that actually connects these together. All I could find is this:

@MainThread
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);

@MainThread
    public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        if (mStatus != Status.PENDING) {
            switch (mStatus) {
                case RUNNING:
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task is already running.");
                case FINISHED:
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task has already been executed "
                            + "(a task can be executed only once)");
            }
        }

        mStatus = Status.RUNNING;

        onPreExecute();

        mWorker.mParams = params;
        exec.execute(mFuture);

        return this;
    }

Here when AsyncTask.execute() is called, onPreExecute() is called. But without any connection to doInBackground the task works just fine. I feel like I'm missing some fundamental logic or process of java or android. Plz, help me with this unsolved question in mind. Sample code is shown below. Thank you in advance.

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mLoadingIndicator.setVisibility(View.VISIBLE);
    }

    @Override
    protected String[] doInBackground(String... params) {

        /* If there's no zip code, there's nothing to look up. */
        if (params.length == 0) {
            return null;
        }

        String location = params[0];
        URL weatherRequestUrl = NetworkUtils.buildUrl(location);

        try {
            String jsonWeatherResponse = NetworkUtils
                    .getResponseFromHttpUrl(weatherRequestUrl);

            String[] simpleJsonWeatherData = OpenWeatherJsonUtils
                    .getSimpleWeatherStringsFromJson(MainActivity.this, jsonWeatherResponse);

            return simpleJsonWeatherData;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(String[] weatherData) {
        // COMPLETED (19) As soon as the data is finished loading, hide the loading indicator
        mLoadingIndicator.setVisibility(View.INVISIBLE);
        if (weatherData != null) {
            // COMPLETED (11) If the weather data was not null, make sure the data view is visible
            showWeatherDataView();
            /*
             * Iterate through the array and append the Strings to the TextView. The reason why we add
             * the "\n\n\n" after the String is to give visual separation between each String in the
             * TextView. Later, we'll learn about a better way to display lists of data.
             */
            for (String weatherString : weatherData) {
                mWeatherTextView.append((weatherString) + "\n\n\n");
            }
        } else {
            // COMPLETED (10) If the weather data was null, show the error message
            showErrorMessage();
        }

Solution

  • I guess you shouldn't waste time on AsyncTask since it is deprecated.

    Instead you should focus on coroutines, recommended by google here , or some other state of the art framework to achive what you want (e.g. rx java)