Search This Blog

Support my cause by downloading

Sunday, 12 May 2013

Android Download Manager Example , Controlling download in android application

Android provide download manager to download different kind of data. Download Manager make developer life much easier. Handling download becomes very easy.
DownloadManager class support only after API 9

Implementing DownloadManager is easy. Lets have a look how we can start downloading using DownloadManager  in android application

    /**
     * Start Download
     */
    public void startDownload() {
        DownloadManager mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Request mRqRequest = new Request(
                Uri.parse("http://androidtrainningcenter.blogspot.in/2012/11/android-webview-loading-custom-html-and.html"));
        mRqRequest.setDescription("This is Test File");
//        mRqRequest.setDestinationUri(Uri.parse("give your local path"));
        long idDownLoad=mManager.enqueue(mRqRequest);
    }



Request mRqRequest = new Request(
Uri.parse("http://androidtrainningcenter.blogspot.in/2012/11/android-webview-loading-custom-html-and.html")); allow you request from DownloadManager to start downloading. You can set your custom Description using Request class.

Handling Download : Stopping, Removing and opening download file

When you start download request, it return you one id. Application can handle download using that id

long idDownLoad=mManager.enqueue(mRqRequest);
mManager.remove(idDownLoad);
try {
mManager.openDownloadedFile(idDownLoad);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Catching Action Using BroadCastReceiver And Notify User

Take on BroadCastReceiver and Register it. You will ACTION_DOWNLOAD_COMPLETE if application register this Intent-Filter.

    DownLoadComplte mDownload;

    @Override
    protected void onStart() {
        super.onStart();
        mDownload = new DownLoadComplte();
        registerReceiver(mDownload, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mDownload);
    }

    private class DownLoadComplte extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase(
                    DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                Toast.makeText(context, "Download Complte", Toast.LENGTH_LONG)
                        .show();
            }
        }
    }

Viewing your downloaded File


public void viewDownload() {
Intent mView = new Intent();
mView.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(mView);
}
Android News and source code