Search code examples
androidandroid-studiodownloadkotlinandroid-download-manager

how to use DownloadManager columns


i'm wondering how to use DownloadManager columns like COLUMN_ID because it gives me the constant value when i use it directly I'm new to android programming (c# background) so i need a little help with some basics in android, i've read android developers guide but it lacks examples so it's worthless
i miss c# guide ;(
this is my code :

fun download(url: String, name: String) {
    //start download request
    var request = DownloadManager.Request(Uri.parse(url))
    request.setVisibleInDownloadsUi(true)
    request.allowScanningByMediaScanner()
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    request.setDestinationInExternalPublicDir("a destination", "$name.pdf")
    // get download service and enqueue file
    val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    manager.enqueue(request)
    var x = (DownloadManager.COLUMN_ID)
    Toast.makeText(applicationContext,x ,Toast.LENGTH_SHORT).show()
    //or 
    //var x = (DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
    //Toast.makeText(applicationContext,x ,Toast.LENGTH_SHORT).show()
}

the Toast text was:

_id (for COLUMN_ID)             
total_size(for COLUMN_TOTAL_SIZE_BYTES)

Solution

  • Once you receive a broadcast with the download id , you can use the id to fetche details related to the download. In your broadcast receiver you get the download id like this intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID. You take this id , and query the download manger.

        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor cursor = downloadManager.query(query);
    

    Once you get the cursor , you can run a loop like this .

         if (cursor.moveToFirst()) {
            if (cursor.getCount() > 0) {
    
                int statusOfTheDownload = cursor.
            getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                String fileUri = cursor.
            getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
    
            }
        }