Android Back button behaves unpredictably on Activity started from Intent
<p>In my application I have 3 activities:</p>

<ul>
<li><code>MainActivity</code>, which is the main screen which comes up when launching the app</li>
<li><code>SettingsActivity</code>, which is started from <code>MainActivity</code></li>
<li><code>DownloadActivity</code>, which is started from <code>SettingsActivity</code>.</li>
</ul>

<p><code>DownloadActivity</code> presents a list of in-app content for users to download. The actual download is handled by Android's <code>DownloadManager</code>, which displays a notification for the downloads in progress. Tapping that notification will fire an intent, which will take the user to <code>DownloadActivity</code>.</p>

<p>Now if I do the following:</p>

<ol>
<li><p>Start the app, go to <code>SettingsActivity</code>, from there to <code>DownloadActivity</code>.</p></li>
<li><p>Start a download, then hit Back twice to go back to <code>MainActivity</code>.</p></li>
<li><p>Pull down the notifications and tap the download nofification, which takes me back to <code>DownloadActivity</code>.</p></li>
<li><p>Hit Back.</p></li>
<li><p>Repeat steps 3 and 4 twice.</p></li>
</ol>

<p>The first time I execute step 4, the Back button will take me straight from <code>DownloadActivity</code> to <code>MainActivity</code> – the last activity the app displayed before I hit the notification, which is what I want.</p>

<p>The second time, however, the Back button will reveal a second <code>DownloadActivity</code> underneath the current one, and I need to hit Back a second time to get back to <code>MainActivity</code>.</p>

<p>The third time, there is a stack of 4 <code>DownloadActivity</code> instances, requiring four presses of the <code>Back</code> button to return to <code>MainActivity</code>.</p>

<p>The code that handles the tap is the following:</p>

<pre><code>Intent downloadIntent = new Intent(activity.getApplicationContext(), downloadActivity.class);
downloadIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
activity.getApplicationContext().startActivity(downloadIntent);
</code></pre>

<p>(<code>activity</code> is a reference to the activity which started the download.)</p>

<p>What is causing this odd behavior, and how can I make the Back button always return to the last activity the app displayed?</p>