Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat happens to an AsyncTask when the launching activity is stopped/destroyed while it is still running?
    text
    copied!<p>I've seen few questions nearly identical to mine, but I couldn't find a complete answer that satisfies all my doubts.. so here I am.. Suppose that you have an activity with an inner class that extends the <code>AsyncTask</code> class like this:</p> <pre class="lang-java prettyprint-override"><code>public class MyActivity extends Activity { private class DownloadImageTask extends AsyncTask&lt;String, Void, Bitmap&gt; { protected Bitmap doInBackground(String... urls) { return DownloadImage(urls[0]); } protected void onPostExecute(Bitmap result) { ImageView img = (ImageView) findViewById(R.id.img); img.setImageBitmap(result); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new DownloadImageTask().execute("http://mysite.com/image.png") } } </code></pre> <p>Suppose that the activity is paused or destroyed (maybe the two cases are different) while the <code>DownloadImageTask</code> is still running in background.. then, the <code>DownloadImageTask</code>'s methods that run on the activity UI thread can be triggered and the <code>DownloadImageTask</code> may try to access Activity's methods (it is an inner class, so it can access the methods and instance variables of the outer class) with a paused or destroyed Activity, like the call to <code>findViewByID</code> in the example below.. what happens then? Does it silently fail? Does it produce any exception? Will the user be notified that something has gone wrong? </p> <p>If we should take care that the launching thread (the Activity in this case) is still alive when running-on-UI methods are invoked, how can we accomplish that from within the <code>AsyncTask</code>?</p> <p>I'm sorry if you find this as a duplicate question, but maybe this question is a bit more articulated and someone can answer with greater detail</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload