[Android开发] 使用DownloadManager下载

主要使用DownloadManager.Request进行下载。

可选

  • 注册一个BroadcastReceiver来监听下载完成,并使用Callback来执行下载完成后的事件。
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
context.registerReceiver(downloadReceiver, filter);
  • 使用DownloadManager.Query查询是否下载成功。

  • 设置Notification。

request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  • 结合网络状况下载。
// Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
// Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(false);

代码

  • DownloadHelper.java
package com.example.android.networkconnect;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.app.DownloadManager.Query;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;

/**
 * Download file helper.
 */
public class DownloadHelper {
    private DownloadManager downloadManager;
    private Request request;
    private long downloadId = -1;
    /**
     * Broadcast when the download has successfully completed.
     */
    private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (completeDownloadId == downloadId) {
                // if download successful
                if (getInt(downloadId, DownloadManager.COLUMN_STATUS) == DownloadManager.STATUS_SUCCESSFUL) {
                    mDownloadDoneCallback.onDownloadDone();
                }
            }
        }
    };
    private DownloadDoneCallback mDownloadDoneCallback;

    public DownloadHelper(Context context, String uri, DownloadDoneCallback downloadDoneCallback) throws Exception {
        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(uri);
        request = new Request(downloadUri);
        String filename = downloadUri.getLastPathSegment();
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
        request.setTitle(filename);
        request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        mDownloadDoneCallback = downloadDoneCallback;

        // Set filter to only when download is complete and register broadcast receiver
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        context.registerReceiver(downloadReceiver, filter);
    }

    /**
     * Start downloading.
     */
    public void start() {
        if (request == null) {
            return;
        }
        //Enqueue a new download and same the referenceId
        downloadId = downloadManager.enqueue(request);
    }

    /**
     * Get int value of a column for the id.
     *
     * @param id         filter id.
     * @param columnName column name.
     * @return first value of the column for the id.
     */
    private int getInt(long id, String columnName) {
        int result = -1;
        Cursor cursor = null;
        try {
            Query query = new Query().setFilterById(id);
            cursor = downloadManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                result = cursor.getInt(cursor.getColumnIndex(columnName));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return result;
    }

    /**
     * Callback when the download has successfully completed.
     */
    public interface DownloadDoneCallback {
        public void onDownloadDone();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值