Declaring AsyncTask types

AsyncTask is a generically typed class, and exposes three type parameters:

abstract class AsyncTask<Params, Progress, Result>

When we declare an AsyncTask subclass, we'll specify types for Params, Progress, and Result; for example, if we want to pass a String parameter to doInBackground, report progress as a Float, and return a Boolean result, we would declare our AsyncTask subclass as follows:

public class MyTask extends AsyncTask<String, Float, Boolean>

If we don't need to pass any parameters, or don't want to report progress, a good type to use for those parameters is java.lang.Void, which signals our intent clearly, because Void is an uninstantiable class representing the void keyword.

Let's take a look at a first example, performing an expensive calculation in the background and reporting the result to the main thread:

public class PrimesTask
extends AsyncTask<Integer, Void, BigInteger> {
  private TextView resultView;

  public PrimesTask(TextView resultView) {
    this.resultView = resultView;
  }

  @Override
  protected BigInteger doInBackground(Integer... params) {
    int n = params[0];
    BigInteger prime = new BigInteger("2");
    for (int i=0; i<n; i++) {
      prime = prime.nextProbablePrime();
    }
    return prime;
  }

  @Override
  protected void onPostExecute(BigInteger result) {
      resultView.setText(result.toString());
  }
}

Here, PrimesTask extends AsyncTask, specifying the Params type as Integer so that we can ask for the nth prime, and the Result type as BigInteger.

We pass a TextView to the constructor so that PrimesTask has a reference to the user interface that it should update upon completion.

We've implemented doInBackground to calculate the nth prime, where n is an Integer parameter to doInBackground, and returned the result as BigInteger.

In onPostExecute, we simply display the result parameter to the view we were assigned in the constructor.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

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

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