如何在安卓设备中从URL下载文件?

4
什么是从URL下载文件的最佳方法?我尝试使用DownloadManager。但是我不知道如何获取已下载文件的Uri。这是我的代码:
   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)
        }

也许现在有更好的方式来下载文件并获取它的Uri,请帮助我。

2个回答

6
如何从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

    }

在调用此方法之前,请检查运行时权限:

Manifest.permission.WRITE_EXTERNAL_STORAGE

5
请尝试这段代码。
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);

}

附加广播接收器

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();
} 

谢谢您的回答。但是我如何获取已下载文件的Uri? - Android

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接