I am encountering difficulties while attempting to download a PDF file in my Android app using the DownloadManager
. I have provided my implementation below:
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)
}
}
This is My Fragment from where i calling to download.
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()
}
}
And the interface i used
interface Downloader {
fun downloadFile(url : String) : Long
}
The issue is that the PDF is not being downloaded, and there is no error in log-cat. I am not sure what might be causing this problem. I have checked the URL, and it seems to valid & working on browser. Can someone please review my code and point out any potential issues or suggest improvements? Additionally, is there a better way to download PDFs in Android using Kotlin?
Your url is http, not https
so Android security policy prevents the download by default
Add this to your Manifest application
tag to bypass the check:
android:usesCleartextTraffic="true"