Executing AsyncTasks

Having implemented doInBackground and onPostExecute, we want to get our task running. There are two methods we can use for this, each offering different levels of control over the degree of concurrency with which our tasks are executed. Let's look at the simpler of the two methods first:

public final AsyncTask<Params, Progress, Result> execute(Params… params)

The return type is the type of our AsyncTask subclass, which is simply for convenience so that we can use method chaining to instantiate and start a task in a single line and still record a reference to the instance:

class MyTask implements AsyncTask<String,Void,String>{ … }
MyTask task = new MyTask().execute("hello");

The Params… params argument is the same Params type we used in our class declaration, because the values we supply to the execute method are later passed to our doInBackground method as its Params… params arguments. Notice that it is a varargs parameter, meaning that we can pass any number of parameters of that type (including none).

Note

Each instance of AsyncTask is a single-use object—once we have started an AsyncTask, it can never be started again, even if we cancel it or wait for it to complete first.

This is a safety feature, designed to protect us from concurrency issues such as the race condition we saw in Chapter 1, Building Responsive Android Applications.

Executing PrimesTask is straightforward—we need Activity, which constructs an instance of PrimesTask with a view to update, then invokes execute with a suitable value for n:

public class PrimesActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_example_1);
    final TextView resultView =
      (TextView) findViewById(R.id.result);
      Button goButton = (Button) findViewById(R.id.go);

      goButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
            public void onClick(View view) {
                new PrimesTask(resultView).execute(500);
      }
    });
  }
}

Great! We're not blocking up the main thread, so our app is nice and responsive, but we can do better.

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

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