Search code examples
androidfiledownloadcursorsize

Android with DownloadManager get total file size


I have researched every where but no any solution. I have a snippet code that run and get the total file size normally while in debug mode of eclipse. But when i run the project the value of sizeOfDownloadingFile only return -1. Please help me, I compile with Android 22, thanks in advance.

 long id = downloadManager.enqueue(request);
            Cursor cursor = downloadManager.query(new DownloadManager.Query()
                    .setFilterById(id));
            if (!cursor.moveToFirst()) {
                Log.v("DownloadManagerService", "download list is empty");
                return;
            }
            int sizeOfDownloadingFile = 0;
            sizeOfDownloadingFile = cursor.getInt(cursor
                    .getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            Log.d("DownloadManagerService",
                    "File size of film " + mFilm.getmTitle() + " is "
                            + sizeOfDownloadingFile);

Solution

  • If you call your code in main thread try:

    new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    check here size of your downloading file
                }
            },500);
    

    When you are in debug mode downloader propably start download and you have a valid value, but if you ran app normaly downloader have to connect to server and doanload file, this sometimes take more time than execution of your code.