0

I am trying to know how to make the AsyncTask survives the screenOrientation change. So, I created an example for a MainActivity with AsyncTask. As shown in the code below, in the doInBackground() method I print the incremented value of the variable "i" each second upto 7 seconds, and I publish the value of the variable "i" using publishProgress() and display it in the TextView. while the value of varibale "i" is being published I changed the orientation of the device and I expected the App will crash, but what happened is, that the the screenOrientation has changed and the value of the variable "i" was being published and normally displayed in the TextView without crash.

Is the AsyncTask I created not a suitable example to learn how to survive the screenOrientation?

MainActivity

public class MainActivity extends AppCompatActivity {

private final static String TAG = MainActivity.class.getSimpleName();

private TextView mtv11Up = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.mtv11Up = (TextView) findViewById(R.id.tv11_up);
    new ATRetain().execute();
}

private class ATRetain extends AsyncTask<Void, Integer, Void> {

    private long mStartTime;
    private int i = 0;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        this.mStartTime = TimeUtils.getTSSec();
    }

    @Override
    protected Void doInBackground(Void... params) {

        Log.i(TAG, "started");

        while((TimeUtils.getTSSec() - this.mStartTime) <= 7) {
            Log.i(TAG, "i: " + (++i));
            publishProgress(i);
            SystemClock.sleep(1000);
        }

        Log.i(TAG, "finished");
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        mtv11Up.setText(String.valueOf(values[0]));
    }
}
}
Amrmsmb
  • 1
  • 27
  • 104
  • 226

1 Answers1

0

AsyncTask create separate thread from UI Thread when orientation changes it recreated it self but AsyncTask is still running because it separate Background thread.

While doing some important work you can lock the screen orientation for some time until AsyncTask will complete then unlock.

Lock:

 protected void onPreExecute() {
    // ....
   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
   }

Unlock:

protected void onPostExecute(String result) {
     // ...
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
   }
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41