码迷,mamicode.com
首页 > 其他好文 > 详细

使用DownloadManager实现下载功能

时间:2015-02-26 20:21:44      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

使用Android自带的DownloadManager实现下载功能

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(APK_URL));
                request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, DOWNLOAD_FILE_NAME);
                request.setTitle(getString(R.string.download_notification_title));
                request.setDescription("meilishuo desc");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setVisibleInDownloadsUi(false);
                // request.allowScanningByMediaScanner();
                // request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
                // request.setShowRunningNotification(false);
                // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
                request.setMimeType("application/cn.trinea.download.file");
                downloadId = downloadManager.enqueue(request);

downloadManager.enqueue是加入下载请求到下载管理类中,并且会返回一个下载的ID。

request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);大文件只能在wifi下下载

需要注册一个下载完成的广播,自定义这个广播

class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            /**
             * get the id of download which have download success, if the id is my id and it's status is successful,
             * then install it
             **/
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (completeDownloadId == downloadId) {
                initData();
                updateView();
                // if download successful, install apk
                if (downloadManagerPro.getStatusById(downloadId) == DownloadManager.STATUS_SUCCESSFUL) {
                    String apkFilePath = new StringBuilder(Environment.getExternalStorageDirectory().getAbsolutePath())
                            .append(File.separator).append(DOWNLOAD_FOLDER_NAME).append(File.separator)
                            .append(DOWNLOAD_FILE_NAME).toString();
                    install(context, apkFilePath);
                }
            }
        }
    };

这里的intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);的DownloadManager.EXTRA_DOWNLOAD_ID是DownloadManager类里的参数,使用下面方法注册广播

/** register download success broadcast **/
        registerReceiver(completeReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
用到的IntentFilter是下载完成的Filter

然后会通知这个广播,并且返回的intent里面包含了DownloadManager.EXTRA_DOWNLOAD_ID的参数。

关于DownloadManager的其他用法可以查看api文档


这里再介绍下DownloadManager.Query的用法。

显而易见Query是内部类。有query.setFilterById和query.setFilterByStatus两个方法,

query.setFilterById就是把downloadManager.enqueue返回的id放进去作为查询的条件;

query.setFilterByStatus(DownloadManager.STATUS_FAILED|DownloadManager.STATUS_PENDING|DownloadManager.STATUS_RUNNING|DownloadManager.STATUS_SUCCESSFUL);可以进行拼接查询的条件。

Cursor cur = downloadManager.query(query);

这里用的Query查询Downloads的数据库,但是只可以查询本应用下载的数据,

/**
                         * 使用DownloadManager.Query查询Downloads的DB,但是在stackoverflow中的解释是
                         * You can‘t access this DB from my application. For your own downloads, 
                         * use DownloadManager.Query to check on your download status. Data about downloads is not shared to other apps.
                         */

所以要是想通过DownloadManager.Query查询系统所有的下载记录是不可行的。

但是需求有要怎么办呢?

记得ApiDemo里有用户联系人使用Uri的方式查询联系人contacts,进入Root Explore观察com.android.providers.downloads包里的DB数据库内容时,发现下载的记录里有content://media/external/file/452122

这种内容,所以可以这样获取到下载的文件

Cursor cursor = getContentResolver().query(Uri.parse("content://media/external/file"), null, null, null, null);
测试下返回的字段

/*String[] downNames = cursor.getColumnNames();
                        String str = "";
                        for(int i=0;i<downNames.length;i++){
                        	str += downNames[i]+",";
                        }*/
                        if(cursor!=null&&cursor.moveToLast()){
//                        	cursor.moveToPrevious()
                        	String displayname = cursor.getString(cursor.getColumnIndex("_display_name"));
                        	String name = cursor.getString(cursor.getColumnIndex("name"));
                        	String title = cursor.getString(cursor.getColumnIndex("title"));
                        	String description = cursor.getString(cursor.getColumnIndex("description"));
                        	String data = cursor.getString(cursor.getColumnIndex("_data"));
                        	String bucket = cursor.getString(cursor.getColumnIndex("bucket_display_name"));
                        	downloadTip.setText(displayname+","+name+","+title+","+description+","+data+","+bucket);
                        }

根据自己需求提取字段。




使用DownloadManager实现下载功能

标签:

原文地址:http://blog.csdn.net/fancylovejava/article/details/43955405

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!