Android How to - Handle AsyncTask interruption during configuration change








The following code shows how to Handle AsyncTask interruption during configuration change.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
//from ww w. j a v a 2  s .  com
import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;
public class MainActivity extends Activity {

   private Worker worker;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      worker = (Worker) getLastNonConfigurationInstance();
      if (worker == null) {
         worker = new Worker();
         worker.execute();
      }
      worker.connectContext(this);
   }

   @Override
   protected void onDestroy() {
      super.onDestroy();
      worker.disconnectContext();
   }

   @Override
   public Object onRetainNonConfigurationInstance() {
      return worker;
   }
}
class Worker extends AsyncTask<Void, Void, String> {

   private Activity context;

   public void connectContext(Activity context) {
      this.context = context;
   }

   public void disconnectContext() {
      this.context = null;
   }

   @Override
   protected String doInBackground(Void... params) {
      try {
         Thread.sleep(3000);
      } catch (InterruptedException e) {
      }
      return "Work done!";
   }

   @Override
   protected void onPostExecute(String result) {
      if (context != null) {
         Toast.makeText(context, result, Toast.LENGTH_LONG).show();
      }
   }
}