尝试使用android的DownloadManager服务,但始终收到404作为原因。 这是排队请求的代码:
val downloadManager = applicationContext.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val request = DownloadManager.Request(uri)
request.setAllowedOverRoaming(true)
request.setAllowedOverMetered(true)
request.setVisibleInDownloadsUi(false)
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
//TODO : do we need to wait here ??
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(baseSessionActivity, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), 0);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS , File(absoluteURL).name)
headers?.forEach { pair ->
request.addRequestHeader(pair.first, pair.second)
}
return downloadManager.enqueue(request)
然后这是我收到ACTION_DOWNLOAD_COMPLETE意向后读取状态的代码:
val query = DownloadManager.Query()
query.setFilterById(downloadId)
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val cursor = downloadManager.query(query)
cursor?.let {
if (cursor.moveToFirst()) {
var reasonIndex = cursor.getColumnIndex(DownloadManager.COLUMN_REASON)
var reason = cursor.getInt(reasonIndex)
var status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
我在磁盘上看不到文件,因此404正确。如果我的代码有任何错误,请告诉我。谢谢