Devrath
Devrath

Reputation: 42854

How to download a file on click of a view in android

What i am having ?

Here patientAttachment.getFile_path() have the link of the url that has image .


 vObjPatientMedication.downloadId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
                myWebLink.setData(Uri.parse(patientAttachment.getFile_path()));
                activity.startActivity(myWebLink);

            }
        });

What now is happening: i am displaying the image in browser

What i am trying to achieve: i want to initiate the download of that file(file can be pdf/image/word) to any default location where downloading is taken care by android.

How to achieve this ?

Upvotes: 0

Views: 47

Answers (1)

Mattia Maestrini
Mattia Maestrini

Reputation: 32790

You can use DownloadManager:

DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uriString));
downloadManager.enqueue(request);

You should also register a receiver to know when a download completes:

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

BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
    public void onReceive(Context ctxt, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            //Your code
        }
    }
};

Upvotes: 2

Related Questions