我在尝试使用
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,
//TODO set the name of pdf
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 {
// inflate the layout and bind to the _binding
_binding = FragmentUserBinding.inflate(inflater, container, false)
binding.button.setOnClickListener {
val url = "http://dtu.ac.in/Web/notice/2023/dec/file1250.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 URL如下:http://dtu.ac.in/Web/notice/2023/dec/file1250.pdf http://dtu.ac.in/Web/notice/2023/dec/file1242.pdf http://dtu.ac.in/Web/notice/2023/dec/file1237.pdf
问题是PDF没有被下载,并且log-cat中没有错误。我不确定是什么原因导致这个问题。我已经检查了 URL,它似乎在浏览器上有效且工作。有人可以检查我的代码并指出任何潜在问题或提出改进建议吗?此外,如果有更好的方法使用 Kotlin 在 Android 中下载 PDF,我将不胜感激。
提前感谢您的帮助!
您的网址是 http,而不是
https
,因此 Android 安全策略默认阻止下载
将此添加到您的清单
application
标签中以绕过检查:
android:usesCleartextTraffic="true"