Android Download Manager

Download Manager

DownloadManager is Android API(above 2.3).
This has download features.

Code

file : File destination URL

DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(file);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(uri.getLastPathSegment());
request.setDescription(file);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
        | DownloadManager.Request.NETWORK_WIFI);
manager.enqueue(request);
Toast.makeText(this, getString("Download"),Toast.LENGTH_LONG).show();

Problem

  • It doesn’t support https
  • Cannot get progress
  • Cannot handle processing

Basically, DownloadManager is OS support. We cannot handle anything while downloading.
If you want to support https, progress, you need to create downloader by myself.

Download Completion Receiver

To detect finish(fail, success), we need to add BroadCastReceiver.

DownloadManagerReceiver

This receiver catches download finish.

public class DownloadManagerReceiver extends BroadcastReceiver {

  private static final String TAG = "DownloadManagerReceiver";

  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
      Bundle extras = intent.getExtras();
      long id = extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
      if (id != -1) {
        DownloadManager.Query q = new DownloadManager.Query();
        q.setFilterById(id);
        DownloadManager manager = (DownloadManager) context
            .getSystemService(Context.DOWNLOAD_SERVICE);
        Cursor c = manager.query(q);

        if (c.moveToFirst()) {
          // Get download status
          int status = c
              .getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));

          if (status == DownloadManager.STATUS_SUCCESSFUL) {
            // Download success
            // Show results
            Toast.makeText(context,
                context.getString("Success"),
                Toast.LENGTH_SHORT).show();
            // Get local file path
            String path = c.getString(c
                .getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
          } else if (status == DownloadManager.STATUS_FAILED) {
            // Failed
            Toast.makeText(context,
                context.getString(R.string.download_failed), Toast.LENGTH_LONG)
                .show();
          }
        }
      }
    }
  }
}

AndroidManifest.xml

<receiver android:name=".web.DownloadManagerReceiver">
 <intent-filter>
   <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
 </intent-filter>
</receiver>