---
title: "android DownloadManager"
author: "sunj"
date: "2018-04-10T12:52:31Z"
tags: []
categories: ["移动开发"]
slug: "android-downloadmanager"
draft: false
lastmod: "2018-04-10T12:52:31Z"
id: 2416141
url: "https://sunj.iteye.com/blog/2416141"
---

From： https://www.jianshu.com/p/46fd1c253701


    private static long mTaskId = -1;

    /*
     * android system api to download
     */
    public static void download(Context context, String urlStr, String filename) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlStr));
        request.setAllowedOverRoaming(false);//漫游网络是否可以下载

        //设置文件类型，可以在下载结束后自动打开该文件
//        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
//        String mimeString = mimeTypeMap.getMimeTypeFromExtension(
//                MimeTypeMap.getFileExtensionFromUrl(urlStr));
//        request.setMimeType(mimeString);

        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(true);

        //sdcard的目录下的download文件夹，必须设置
        request.setDestinationInExternalPublicDir("/download/", filename);
//        request.setDestinationInExternalFilesDir(context,type, filepath) // 也可以自己指定下载路径

        // 将下载任务加入队列
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        //加入下载队列后会给该任务返回一个long型的id，
        //通过该id可以取消任务，重启任务等等，看上面源码中框起来的方法
        mTaskId = downloadManager.enqueue(request);

//        downloadManager.remove(taskId) //

        context.registerReceiver(mReceiverDownload, new IntentFilter());
    }

    private static BroadcastReceiver mReceiverDownload = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkDownloadStatus();
        }
    };

    private static void checkDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(mTaskId);
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()){
            int status = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
            switch (status){
                case DownloadManager.STATUS_PAUSED:
                    Log.v(TAG, "下载暂停");
                    break;
                case DownloadManager.STATUS_PENDING:
                    Log.v(TAG, "下载延迟");
                    break;
                case DownloadManager.STATUS_RUNNING:
                    Log.v(TAG, "正在下载...");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    Log.v(TAG,"下载完成");
                    // Play Act
                    break;
                case DownloadManager.STATUS_FAILED:
                    Log.v(TAG, "下载失败");
                    break;
            }
        }
    }

希望你可以看到最后这几句，不然你也会被坑的！
1.虽然下载什么的不需要自己操心了，但是建议还是将整个上面四段代码放在Service中执行，因为放在Activity中时，当用户按home键后，即使下载完了，也不会弹出安装界面
2.建议使用startService的方式启动Service，这样不会与Activity生命周期绑定，保证下载完后能顺利安装。
3.Service使用完后要及时地停掉！


作者：Marno
链接：https://www.jianshu.com/p/46fd1c253701
來源：简书
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。