无法使用Android下载管理器获取当前下载文件大小

时间:2014-02-10 11:08:28

标签: android android-download-manager

我调用下面的服务来处理给定URL的下载。正如您在下面的代码段中看到的,我想将当前下载文件大小分配给total_size

但是(使用Eclipse调试器),即使文件正确下载,其值仍为-1。建议?

public class DownloadManagerService extends IntentService {

    public final static String ACTION_DOWNLOAD_STARTED= "com.youzik.app.intent.action.ACTION_DOWNLOAD_STARTED";
    public static final String DATA = "download";
    public static final String URL = "url";

    public DownloadManagerService() {
        super("DownloadManagerService");
    }

    @Override
    protected void onHandleIntent(Intent service) {
        Request request = new Request(Uri.parse(service.getStringExtra(URL)));
        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        long downloadId = downloadManager.enqueue(request);

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

        if (!cursor.moveToFirst()) {
            Log.v("DownloadManagerService", "download list is empty");
            return;
        }

        Download dl = new Download();
        dl.setId(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
        dl.setName(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)));
        dl.setUrl(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));

        int total_size = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

        cursor.close();
    }

}

2 个答案:

答案 0 :(得分:0)

Bundle extras = intent.getExtras();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
Cursor c = YOUR_DM.query(q);

if (c.moveToFirst()) {
    int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
    if (status == DownloadManager.STATUS_SUCCESSFUL) {
        // process download
        title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
        // get other required data by changing the constant passed to getColumnIndex
    }
}

答案 1 :(得分:0)

确保您已在Manifest文件中提供所需的用户权限。

ul.dropdown-menu

另外,给予android marshmallow及以上版本的运行时权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />