You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RecyclerView点击条目触发文件下载却未保存问题求助

解决RecyclerView条目点击下载文件无实际保存的问题

1. 检查存储权限配置

  • Android 13+ 若写入公共存储,需动态申请对应细分权限(如READ_MEDIA_IMAGES);写入应用私有目录(如内部存储getFilesDir()、外部私有存储getExternalFilesDir(null))无需动态权限,但要确保路径调用正确。
  • 动态权限申请示例(Kotlin):
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityResultContracts.RequestPermission()
}

2. 验证文件保存路径合法性

  • 禁止硬编码路径,使用系统API获取合法目录:
    • 内部私有存储:context.filesDir.absolutePath
    • 外部私有下载目录:context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
  • 提前创建目录并打印日志确认:
File saveDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "MyAppDownloads");
if (!saveDir.exists()) {
    boolean isCreated = saveDir.mkdirs();
    Log.d("DownloadDebug", "目录创建结果:" + isCreated);
}

3. 修正下载逻辑的IO操作

  • 必须在子线程/协程中执行IO操作,避免主线程阻塞导致写入失败。
  • 使用try-with-resources自动关闭流,确保数据完整写入:
val url = URL(targetUrl)
val connection = url.openConnection() as HttpURLConnection
connection.connect()

val inputStream = connection.inputStream
val outputFile = File(saveDir, "target_file.pdf")

inputStream.use { input ->
    FileOutputStream(outputFile).use { output ->
        input.copyTo(output)
    }
}

4. 补全异常捕获逻辑

  • 原代码大概率未捕获IO/网络异常,导致失败仍提示成功。添加异常日志排查:
try {
    // 下载逻辑
} catch (e: IOException) {
    Log.e("DownloadError", "IO异常:${e.message}", e)
    // 更新UI提示下载失败
} catch (e: Exception) {
    Log.e("DownloadError", "未知错误:${e.message}", e)
}

5. 检查下载文件完整性

  • 下载完成后校验文件大小,若为0说明流读取或网络请求存在问题:
if (outputFile.exists() && outputFile.length() == 0) {
    Log.e("DownloadDebug", "文件为空,下载失败")
    outputFile.delete()
}

内容的提问来源于stack exchange,提问作者Reza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 05:36:01