Android with DownloadManager get total file size

2019-09-04 13:30发布

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);

2条回答
\"骚年 ilove
2楼-- · 2019-09-04 14:10

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.

查看更多
该账号已被封号
3楼-- · 2019-09-04 14:10

I found the problem, this caused by method setFilterById() processing. After I change the code to this I can get the right result now, but I recommend the Adam's code:

id = downloadManager.enqueue(request);
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Thread.sleep(1000);
        cursor = downloadManager.query(query);
        if (!cursor.moveToFirst()) {
            Log.v("DownloadManagerService", "download list is empty");
            return;
        }
        int size = 0;
        size = cursor.getInt(cursor
                .getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
        Log.v("DOWNLOADING FILE SIZE", "File size of film " + f.getmTitle()
                + " is " + size);
        cursor.close();
查看更多
登录 后发表回答