无法使用downloadManager从Android中的链接下载PDF

42fyovps  于 5个月前  发布在  Android
关注(0)|答案(2)|浏览(97)

我在尝试使用DownloadManager在我的Android应用程序中下载PDF文件时遇到了困难。我在下面提供了我的实现:

class AndroidDownloader(private val context: Context) : Downloader {
    private val downloadManager = context.getSystemService(DownloadManager::class.java)

    override fun downloadFile(url: String): Long {
        val request = DownloadManager.Request(Uri.parse(url))
            .setMimeType("application/pdf")
            .setTitle("Downloading PDF")
            .setDescription("Downloading...")
            .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalFilesDir(
                context,
                Environment.DIRECTORY_DOWNLOADS,
                File.separator + "my.pdf"
            )
        return downloadManager.enqueue(request)
    }
}

字符串
这是我打电话下载的片段。

class UserFragment : Fragment() {

    private var _binding: FragmentUserBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentUserBinding.inflate(inflater, container, false)
        binding.button.setOnClickListener {
            val url = "http://www.africau.edu/images/default/sample.pdf"
            println(url)
            downloadPdf(url)
        }
        return binding.root
    }
    private fun downloadPdf(pdfUrl: String) {
        val downloader = AndroidDownloader(requireContext())
        downloader.downloadFile(pdfUrl)
        Toast.makeText(requireContext(), "Download clicked for $pdfUrl", Toast.LENGTH_SHORT).show()
    }
}


我使用的界面

interface Downloader {
    fun downloadFile(url : String) : Long
}


问题是PDF没有被下载,并且log-cat中没有错误。我不知道是什么原因导致了这个问题。我已经检查了URL,它似乎是有效的&在浏览器上工作。有人可以检查我的代码并指出任何潜在的问题或建议改进吗?此外,如果有更好的方法在Android中使用Kotlin下载PDF,我将非常感谢任何指导。
提前感谢您的帮助!

x7yiwoj4

x7yiwoj41#

您的URL是http,而不是https,因此Android安全策略默认情况下会阻止下载
将此添加到您的Manifest application标记以绕过检查:

android:usesCleartextTraffic="true"

字符串

uajslkp6

uajslkp62#

明白了!当使用DownloadManager在Android上下载PDF时,有几件事可能会出错:
1.检查URL:确保链接直接指向PDF。
1.验证:确保您的应用具有访问互联网和写入存储的权限。
1.网络连接:检查是否有良好的互联网连接。
1.处理错误:注意下载过程中弹出的任何错误。
1.在其他设备上测试:看看它在其他Android设备上的工作方式是否不同。
这些步骤可能有助于找出为什么PDF无法在使用DownloadManager的Android设备上正确下载。

相关问题