androiddownloadandroid-download-manager

Set timeout for Android Download manager after 2 min


How to set the Download manager time out and enable or disable the Download manager after 2 minutes.

fun downloadFile(url: String) {
  val downloadManager = this.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

            val downloadUri = Uri.parse(url)

            val request = DownloadManager.Request(downloadUri).apply {
                try {
                    setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
                        .setAllowedOverRoaming(true)
                        .setTitle(url.substring(url.lastIndexOf("/") + 1))
                        // .setDescription("abc")
                        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                        .setDestinationInExternalPublicDir(
                            Environment.DIRECTORY_DOWNLOADS,
                            url.substring(url.lastIndexOf("/") + 1)
                        )
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
            //TODO to get the Downloading status
            val downloadId = downloadManager.enqueue(request)
            val query = DownloadManager.Query().setFilterById(downloadId)

}

In above code how to handle the timeout with download manager.


Solution

  • You can schedule a new thread to run after x milliseconds using Handler.postDelayed(); In that scheduled thread you use would use DownloadManager.query to access the Cursor object which exposes the download status. If the download status indicates the download isn't completed successfully, you can cancel it using DownloadManager.remove()

    I tested that this works:

    private fun tryDownloadFileButCancelIfTimeout(url: String, millisecondsToTimeoutAfter : Long) {
        val downloadManager = this.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        val downloadUri = Uri.parse(url)
        val request = DownloadManager.Request(downloadUri).apply {
            try {
                setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
                    .setAllowedOverRoaming(true)
                    .setTitle(url.substring(url.lastIndexOf("/") + 1))
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
                    .setDestinationInExternalPublicDir(
                        Environment.DIRECTORY_DOWNLOADS,
                        url.substring(url.lastIndexOf("/") + 1)
                    )
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        val downloadId = downloadManager.enqueue(request)
        // Schedule a new thread that will cancel the download after millisecondsToTimeoutAfter milliseconds
        Handler(Looper.getMainLooper()).postDelayed({
            val downloadQuery = DownloadManager.Query().setFilterById(downloadId)
            val cursor = downloadManager.query(downloadQuery)
            val downloadStatusColumn = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
            cursor.moveToPosition(0)
            val downloadStatus = cursor.getInt(downloadStatusColumn)
            if (downloadStatus != DownloadManager.STATUS_SUCCESSFUL) {
                downloadManager.remove(downloadId)
            }
    
        }, millisecondsToTimeoutAfter)
    }
    

    Posting the code I used to test (can import to Android Studio if you like, simple app with a single download button that starts the download and cancels in five seconds):

    https://github.com/hishamhijjawi/DownloadCancelDemoStackOverflow