如何从Android 10中特定位置的服务器下载任何文件?

问题描述

我从服务器下载文件代码在API级别28和更低版本上可以正常工作,但在API级别29上却无法正常工作。

private fun downloadV(url: String) {
    val fileName = System.currentTimeMillis().toString() + ".mp4"
    val downloaduri = Uri.parse(url)
    val request = DownloadManager.Request(downloaduri)
    request.setAllowednetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
    request.setAllowedOverRoaming(false)
    request.setTitle(fileName)
    request.setDescription(fileName)
    request.setDestinationInExternalPublicDir("/XYZ",fileName)
    request.allowScanningByMediaScanner()
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    downloadManager?.enqueue(request)
}

解决方法

将此行添加到“应用程序”标签中的清单

requestLegacyExternalStorage="true" 
,

一次检查此文档 https://developer.android.com/training/data-storage/shared/documents-files#grant-access-directory

或尝试授予存储的运行时权限

if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},1);
    }

    if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
    }