title: Android DownloadManager, backup files and canceled downloads
body: <p>In my app, I am implementing a mechanism to download data files via DownloadManager. When users start a download, a Cancel button appears next to it, allowing the user to cancel a download in progress.</p>
  
  <p>These data files periodically get updated on the server, so users will want to download the same file again from time to time. File names stay stable across updates.</p>
  
  <p>Since the user may hit Cancel any time during the download, I want to keep the old version around until the download has completed successfully. To this end, I rename the existing file and only then initiate the download. If the user cancels the download (also if the download fails for some reason), I want to restore the backup file to its original location.</p>
  
  <p>For the Cancel case, I originally added the following code to run when the Cancel button is clicked:</p>
  
  <pre><code>if (downloadManager.remove(reference) &gt; 0) {
      if (destFile.exists())
          destFile.delete();
      backupFile.renameTo(destFile);
  }
  </code></pre>
  
  <p>When I refresh a file, the old file gets renamed before the download starts. However, after I cancel the download, both the partial file and the backup are gone.</p>
  
  <p>Since I already use a <code>FileObserver</code> to monitor download progress, I extended it to also watch for file deletion and generate a log message. In the logcat I see two deletion events for the same file, which indicates the partially downloaded file gets deleted, the backup gets renamed and then the renamed backup gets deleted as well.</p>
  
  <p>Fair enough, I thought, apparently DownloadManager takes care of deletion in the background, so I need to watch for that to happen. So I modified the above event handler to just store the file path in a list and not do any file operations just yet. I then modified my <code>FileObserver</code> to compare all deleted files to the list: if it matches, rename the backup file. Additionally, I added log output for each operation.</p>
  
  <p>However, the sequence of events is still effectively the same: now the partially downloaded file gets deleted by the download manager, triggering my <code>FileObserver</code>, which will in turn rename the backup file. After that, the backup file gets deleted.</p>
  
  <p>It looks to me as if the download manager is overzealous: when a download is canceled, it deletes the downloaded file, then checks if it is really gone and retries the deletion if it still finds a file in that path.</p>
  
  <p>How can I get around this and prevent the download manager from deleting files it didn't download?</p>