For the More Curious: More on AsyncTask

In this chapter you saw how to use the last type parameter on AsyncTask, which specifies the return type. What about the other two?

The first type parameter allows you to specify the type of input parameters you will pass to execute(), which in turn dictates the type of input parameters doInBackground(…) will receive. You would use it in the following way:

AsyncTask<String,Void,Void> task = new AsyncTask<String,Void,Void>() {
    public Void doInBackground(String... params) {
        for (String parameter : params) {
            Log.i(TAG, "Received parameter: " + parameter);
        }

        return null;
    }
};

Input parameters are passed to the execute(…) method, which takes a variable number of arguments:

    task.execute("First parameter", "Second parameter", "Etc.");

Those variable arguments are then passed on to doInBackground(…).

The second type parameter allows you to specify the type for sending progress updates. Here is what the code pieces look like:

final ProgressBar gestationProgressBar = /* A determinate progress bar */;
gestationProgressBar.setMax(42); /* Max allowed gestation period */

AsyncTask<Void,Integer,Void> haveABaby = new AsyncTask<Void,Integer,Void>() {
    public Void doInBackground(Void... params) {
        while (!babyIsBorn()) {
            Integer weeksPassed = getNumberOfWeeksPassed();
            publishProgress(weeksPassed);
            patientlyWaitForBaby();
        }
    }

    public void onProgressUpdate(Integer... params) {
        int progress = params[0];
        gestationProgressBar.setProgress(progress);
    }
};

/* Call when you want to execute the AsyncTask */
haveABaby.execute();

Progress updates usually happen in the middle of an ongoing background process. The problem is that you cannot make the necessary UI updates inside that background process. So AsyncTask provides publishProgress(…) and onProgressUpdate(…).

Here is how it works: You call publishProgress(…) from doInBackground(…) in the background thread. This will make onProgressUpdate(…) be called on the UI thread. So you can do your UI updates in onProgressUpdate(…), but control them from doInBackground(…) with publishProgress(…).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
34.229.151.93