How to use DownloadManager on Android 10?

2020-03-26 android android-download-manager

I want to use DownloadManager on Android 10 to download files, and a download progress notification bar will appear.

I use the following code, which can be used normally on devices under Android 9 but not on Android 10 emulator (no error exception message appears). The download progress notification bar does not appear on the notification bar, but I notice This file appeared in the "Files" app of the system and was not downloaded because its raw size (bytes) is always -1.

How can I modify my code so that it can be used on Android 10, thank you very much!

        var request = DownloadManager.Request(Uri.parse(downloadUrl))
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, saveName)
        } else {
            request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, saveName)
            DownloadManager.Request.NETWORK_MOBILE or DownloadManager.Request.NETWORK_WIFI

Screenshot of the system app "File"

Screenshot of the system app "File"2


From the test results, this problem may be a bug in the simulator, because I did not test this problem on real devices (Samsung s10, Samsung note9, Xiaomi 8, Google nexus6P), but I have no more real devices , So if you have this problem with other real devices, please let me know.