Android DownLoadManager 使用

  1. 布局文件



    
  1. Activity代码
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final String PATH = "https://www.python.org/ftp/python/2.7.14/python-2.7.14.amd64.msi";
    private long mId;
    private DownloadManager mDownloadManager;
    private DownloadManager.Query mQuery;
    private Uri mUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * 下载点击
     */
    public void downLoad(View view) {
        // 获取DownloadManager对象
        mDownloadManager = (DownloadManager) this.getSystemService(DOWNLOAD_SERVICE);
        // 创建一个下载请求
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(PATH));
        // 设置内存卡保存的文件夹与文件名
        // setDestinationUri
        // setDestinationInExternalPublicDir
        request.setDestinationInExternalPublicDir("DownloadManagerTest", "python.msi");
        //设置下载中通知栏提示的标题
        request.setTitle("python");
        //设置下载中通知栏提示的介绍
        request.setDescription("python desc");
        // 设置通知是否显示
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 通过setAllowedNetworkTypes方法可以设置允许在何种网络下下载,
        // 也可以使用setAllowedOverRoaming方法,它更加灵活
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        // 文件类型
        request.setMimeType("application/zip");

        // 执行下载,返回downloadId,downloadId可用于后面查询下载信息。若网络不满足条件、Sdcard挂载中、超过最大并发数等异常会等待下载,正常则直接下载。
        mId = mDownloadManager.enqueue(request);

        // 返回移动网络下载的最大值
        Long maxBytesOverMobile = DownloadManager.getMaxBytesOverMobile(this);
        Log.e(TAG, "downLoad: maxBytesOverMobile ---------" + maxBytesOverMobile);
        // 获取建议的移动网络下载的大小
        Long recommendedMaxBytesOverMobile = DownloadManager.getRecommendedMaxBytesOverMobile(this);
        Log.e(TAG, "downLoad: recommendedMaxBytesOverMobile ---------" + recommendedMaxBytesOverMobile);
    }

    /**
     * 取消下载点击
     */
    public void unDownLoad(View view) {
        // 删除下载,若下载中取消下载。会同时删除下载文件和记录。
        mDownloadManager.remove(mId);
    }

    /**
     * 查询存储地址
     */
    public void queryUri(View view) {
        // 获取Uri和下载文件
        mUri = mDownloadManager.getUriForDownloadedFile(mId);
        Log.e(TAG, "queryUri: uri--------" + mUri);
        // 创建一个查询对象
        mQuery = new DownloadManager.Query().setFilterById(mId);
        // 根据查询对象获取一个游标对象
        Cursor cursor = mDownloadManager.query(mQuery);
        if (null != cursor) {
            if (cursor.moveToFirst()) {
                // 获取文件路径
                String fileUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
                Log.e(TAG, "queryUri: fileUri ---------" + fileUri);
                // 获取下载状态
                int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                Log.e(TAG, "queryUri: " + status);
                switch (status) {
                    // 空闲等待中
                    case DownloadManager.STATUS_PENDING:
                        Log.e(TAG, "queryUri: STATUS_PENDING");
                        break;
                    // 暂停中
                    case DownloadManager.STATUS_PAUSED:
                        Log.e(TAG, "queryUri: STATUS_PAUSED");
                        break;
                    // 正在下载
                    case DownloadManager.STATUS_RUNNING:
                        Log.e(TAG, "queryUri: STATUS_RUNNING");
                        break;
                    // 下载成功
                    case DownloadManager.STATUS_SUCCESSFUL:
                        Log.e(TAG, "queryUri: STATUS_SUCCESSFUL");
                        break;
                    // 下载失败
                    case DownloadManager.STATUS_FAILED:
                        Log.e(TAG, "queryUri: STATUS_FAILED");
                        break;
                    default:
                        break;
                }
            }
            cursor.close();
        }
    }

    /**
     * 获取下载信息
     * @param downloadId 下载ID
     * @return
     */
    public int[] getBytesAndStatus(long downloadId) {
        int[] bytesAndStatus = new int[] { -1, -1, 0 };
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = null;
        try {
            c = mDownloadManager.query(query);
            if (c != null && c.moveToFirst()) {
                // 获取已下载字节数
                bytesAndStatus[0] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                // 获取总字节数
                bytesAndStatus[1] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                // 获取当前状态
                bytesAndStatus[2] = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return bytesAndStatus;
    }

    class DownloadStatusObserver extends ContentObserver {

        DownloadStatusObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            int[] bytesAndStatus = getBytesAndStatus(mId);
            //当前大小
            int currentSize = bytesAndStatus[0];
            //总大小
            int totalSize = bytesAndStatus[1];
            //下载状态
            int status = bytesAndStatus[2];

        }

    }

    DownloadStatusObserver observer = new DownloadStatusObserver(new Handler());

    @Override
    protected void onResume() {
        super.onResume();
        getContentResolver().registerContentObserver(mUri, true, observer);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(observer);
    }

}

你可能感兴趣的:(Android DownLoadManager 使用)