I am running an AsyncTask in MainActivity and making it sleep for 10 seconds in the doInBackground()
method. And in between (before the 10 seconds are over), I press the Home button and I am also updating the text in TextView in the onPostExecute()
method of the AsyncTask. My AsyncTask is able to update the view successfully even though my app is in background.
I am not sure how that is possible, by the way, if I press the Back button, then I can see the onDestroy()
method of the activity being called, but still there is no exception when the onPostExecute()
method tries to update the TextView.
public class MainActivity extends AppCompatActivity {
private TextView finalTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
finalTextView = (TextView) findViewById(R.id.finalTextView);
AsyncTaskRunner task = new AsyncTaskRunner();
task.execute("10", "11", "12");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.e("onDestroy", "ActivityDestroyed");
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
@Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0]) * 1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
finalTextView.setText(result);
Log.e("onPostExecute", "" + result);
}
}
}