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]));
}
}
}