Pausing and Resuming Background Work in Android

The AsyncTask mechanism in Android is very easy to use. It provides a way to cancel work gracefully. Unfortunately, it has no way of pausing and resuming work. This presents a problem when an activity needs to pause work when going in to paused or stopped state.

This morning, I spent a bit of time solving that problem. The result is a ThreadControl class that provides pause, resume and cancel semantics. It can be used from any Java thread, including AsyncTask. Source code for a fully working sample project can be found here in GitHub.

Let’s have a look at a very simple example of an activity that controls background work via the ThreadControl class. It also shows how to code the work done in a background thread.

public class MainActivity extends Activity {
  ThreadControl tControl = new ThreadControl();
  int count = 0;

  public void onCreate(Bundle savedInstanceState) {

    AsyncTask<Void, Void, Void> task = 
      new AsyncTask<Void, Void, Void>() {
      protected Void doInBackground(Void... params) {
        try {
          //Do some long running work
          while (true) {
            //Pause work if control is paused.
            //Stop work if control is cancelled.
            if (tControl.isCancelled()) {
        } catch (Exception e) {

        return null;

  protected void onDestroy() {
    //Cancel control

  protected void onPause() {
    //No need to pause if we are getting destroyed 
    //and will cancel thread control anyway.
    if (!isFinishing()) {
      //Pause control.

  protected void onResume() {

The cool thing is that you can control as many background threads as you want using the same ThreadControl object. Of course, all threads must call waitIfPaused() for the same ThreadControl object. Also, the ThreadControl class has no dependency on Android. You can use it from any Java application.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s