Handling Orientation changes with Context and AlertDialog/AsyncTask
<p>I have an activity that loads an AlertDialog like this.</p>

<pre><code>        progressDialog = new ProgressDialog( MyActivity.this );
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("Doing Something");
        progressDialog.setCancelable(false);
        progressDialog.show();
</code></pre>

<p>I also have another class that extends AsyncTask</p>

<pre><code>    private class MyBackgroundTask extends AsyncTask&lt;Void, Void, Boolean&gt; {

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

            ...do stuff
        }

        @Override
        protected void onPostExecute(Boolean result) {

            progressDialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

    }
</code></pre>

<p>If the orientation of the screen changes I get an error about trying to attach to a view that does not exist.  This is because the Activity has been destroyed and the  context has gone away.</p>

<p>So I added this to onDestroy() and it fixed it.</p>

<pre><code>    @Override
    public void onDestroy() {

        if(progressDialog!=null)
            if(progressDialog.isShowing())
                progressDialog.cancel();

        if(background!=null)
            background.cancel(true);
    }
</code></pre>

<p>But this means that I always have to keep a reference to the Dialog and AsyncTask</p>

<p>So I cant do this for example:</p>

<pre><code>new MyAsyncTask().execute();
</code></pre>

<p>In case the orientation changes, equally I can't do this:</p>

<pre><code>    new AlertDialog.Builder(this)
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setTitle( "some title" )
    .setMessage("some message")
    .setPositiveButton(R.string.ok, null)
    .show();
</code></pre>

<p>This does not seem right to me and there must be a better way, I know you can use getApplicationContext() but in some situations this is not viable.</p>

<p>How do I manage this properly?</p>
