Android
Android

Reputation: 279

How to download file from URL in android?

What is the best way to download file from url. I try to use DownloadManager. But I cannot understand how to get Uri of downloaded file . Here is my code:

   file?.let {
            val uri = Uri.parse(it)
            val downloadManager = getSystemService<Any>(Context.DOWNLOAD_SERVICE) as DownloadManager?
            val request = DownloadManager.Request(uri)
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or
                    DownloadManager.Request.NETWORK_MOBILE)
            request.allowScanningByMediaScanner()
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "downloadfileName")
            request.setMimeType("*/*")
            downloadManager?.enqueue(request)
        }

Perhaps today there is a better way to download the file and get it Uri. Please help me

Upvotes: 4

Views: 18535

Answers (2)

Vishal Sojitra
Vishal Sojitra

Reputation: 496

Please try this code

public void downloadPdf(String url, String sem, String title, String branch) {
Uri Download_Uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);

//Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(false);
//Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("Downloading");
//Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Downloading File");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title + "_" + branch + "_" + sem + "Year" + System.currentTimeMillis() + ".pdf");

request.allowScanningByMediaScanner(); 
request. setNotificationVisibility(DownloadManager.Request. VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION)

//Enqueue a new download and same the referenceId
downloadReference = downloadManager.enqueue(request);

}

attach broadcast receiver

BroadcastReceiver attachmentDownloadCompleteReceive = 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);
        openDownloadedAttachment(context, downloadId);
    }
}
};


private void openDownloadedAttachment(final Context context, final long downloadId) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
    int downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
    String downloadLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
    String downloadMimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
    if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
        openDownloadedAttachment(context, Uri.parse(downloadLocalUri), downloadMimeType);
    }
}
cursor.close();
} 

Upvotes: 5

chand mohd
chand mohd

Reputation: 2550

How to download file from Url

fun downloadPdf(baseActivity:Context,url: String?,title: String?): Long {
        val direct = File(Environment.getExternalStorageDirectory().toString() + "/your_folder")

        if (!direct.exists()) {
            direct.mkdirs()
        }
        val extension = url?.substring(url.lastIndexOf("."))
        val downloadReference: Long
         var  dm: DownloadManager
         dm= baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        val uri = Uri.parse(url)
        val request = DownloadManager.Request(uri)
        request.setDestinationInExternalPublicDir(
                "/your_folder",
                "pdf" + System.currentTimeMillis() + extension
        )
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        request.setTitle(title)
        Toast.makeText(baseActivity, "start Downloading..", Toast.LENGTH_SHORT).show()

        downloadReference = dm?.enqueue(request) ?: 0

        return downloadReference

    }

Bofore calling this method do check for Runtime permission:

Manifest.permission.WRITE_EXTERNAL_STORAGE

Upvotes: 6

Related Questions