When/Why to use Android DownloadManager to download remote files

DownloadManager should be used when your app is not dependent on downloaded data to show as a first thing. It queues requested download in device wide download queue, and download data in background. You may not get your data downloaded immediately to display in your app.

If the dependency of your app on remote data is synchronous, then you may want to download data using AsyncTask, and possibly using code like this in it:

InputStream inputStream = new URL(url).openStream();
//Copy input stream to to output stream now. 

But if you don't care about the timing of data download, then you should use DownloadManager like this:

String url = "http://url_to_your_remote-data";
DownloadManager  dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse(url));
request.setDestinationInExternalFilesDir(getApplicationContext(),
        Environment.DIRECTORY_DOWNLOADS, "downloaded_data_filename");
enqueue = dm.enqueue(request);

And don't forget to register broadcast receiver in onCreate() method. That's where you'll receive callback once download is finished. Example:

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            long downloadId = intent.getLongExtra(
                    DownloadManager.EXTRA_DOWNLOAD_ID, 0);

            Uri localUri = dm.getUriForDownloadedFile(enqueue);
            //Do something with your download here...OR query useful params like below. 

            Query query = new Query();
            query.setFilterById(enqueue);
            Cursor c = dm.query(query);
            if (c.moveToFirst()) {
                int columnIndex = c
                        .getColumnIndex(DownloadManager.COLUMN_STATUS);
                if (DownloadManager.STATUS_SUCCESSFUL == c
                        .getInt(columnIndex)) {

                    String uriString = c
                            .getString(c
                                    .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    Log.d("TAG", uriString);
                    
                }
            }
        }
    }
};

registerReceiver(receiver, new IntentFilter(
        DownloadManager.ACTION_DOWNLOAD_COMPLETE));



No comments:

Post a Comment

Scheduling Repeating Local Notifications using Alarm Manager

Learn about Scheduling Repeating Local Notifications using Alarm Manager in this post .