android - 获取文件路径的问题
问题描述
我在 kotlin - android 中使用下载管理器。成功下载文件如下:
fun downloadFirmwareFile(baseActivity: Context, url: String?, title: String?): Long {
val direct = File(Environment.getExternalStorageDirectory().toString() + "/firmware")
if (!direct.exists()) {
direct.mkdirs()
}
val extension = url?.substring(url.lastIndexOf("."))
val downloadReference: Long
var dm: DownloadManager = baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(url)
val request = DownloadManager.Request(uri)
var subPath = "bin" + System.currentTimeMillis() + extension
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOCUMENTS,
subPath)
Log.e("File path >> ", Environment.DIRECTORY_DOCUMENTS + subPath)
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
downloadFirmwareLiveData.postValue("")
var file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), subPath)
if (file.exists()) {
Log.e("path >>>>>>>>>", "path >>>>>>>>>" + file.absolutePath)
}else{
Log.e("path >>>>>>>>>", "path >>>>>>>>> File not exists")
}
return downloadReference
}
在这里,您可以看到我正在尝试获取下载的文件路径,如下所示:
var file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), subPath)
if (file.exists()) {
Log.e("path >>>>>>>>>", "path >>>>>>>>>" + file.absolutePath)
}else{
Log.e("path >>>>>>>>>", "path >>>>>>>>> File not exists")
}
但它给了我:路径>>>>>>>>> 文件不存在
可能是什么问题?请指导。
解决方案
如果您想创建自己的URI
并将其用于下载内容,那么您可以使用以下代码。
首先添加文件provider
。manifest.xml
喜欢
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
文件路径.xml
<paths>
<external-path name="external_files" path="."/>
您现在可以创建自己的URI
并将download manager
文件内容保存在其中。看下面的代码:
fun downloadFirmwareFile(baseActivity: Context, url: String?, title: String?,saveFileUri: Uri): Long {
val downloadReference: Long
val dm: DownloadManager
dm = baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(url)
val request = DownloadManager.Request(uri)
// Here uri is passed and image will be downloaded inside this file--
request.setDestinationUri(saveFileUri)
/* request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOCUMENTS,
"bin" + 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
}
你必须URI
在开始下载之前创建。如下所示:
downlodNowBtn.setOnClickListener {
context?.let {
createImageFile().let { downloadFile ->
try {
// storing URI in a variable, so that it could be used further if required......
downloadedFileUri = Uri.fromFile(downloadFile)
Log.d("tisha==>>","File Uri= ${}")
// replace with your desired url----------------------------
downloadFirmwareFile(it,"https://homepages.cae.wisc.edu/~ece533/images/airplane.png","My photo", Uri.fromFile(downloadFile))
}catch (e: java.lang.Exception){
Log.d("tisha==>>"," ${e.localizedMessage}")
}
}
}
}
@Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
// val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
val storageDir: File? = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File(storageDir,"test.jpg")
}
现在您可以从以前存储的URI
. 喜欢:
val bitmap = BitmapFactory.decodeStream(downloadedFileUri?.let { it1 -> context?.contentResolver?.openInputStream(it1) })
推荐阅读
- c# - 在接口中使用虚拟方法的 C++/CLI/C# 回调
- python - 任何具有良好链接或博客的人都可以通过 apache 气流中的 xcom 功能,
- .net - 现在如何编辑 Pixelsense 应用程序?
- python - 使用 django 2 添加类别的 url
- reactjs - 如何使用 React Native 创建动态数量的组件?
- javascript - 如何使用 exceljs 从 .xls 文件中读取?
- amazon-web-services - 使用联合用户的权利表控制对 Amazon DynamoDB 条目的访问
- c# - 如何在 asp.net core 3 中设置 json 序列化程序设置?
- svn - 通过校验和(SHA Hash)获取存储到 Subversion(SVN)的文件
- java - Classname.Variable 与 Classname 作为变量一起使用