DownloadManager是Android爲開發者提供的一個後臺應用組件,它經過Http層進行文件的下載任務. 1:使用 首先要在AndroidManifest.xml中申請訪問DownloadManager的權限 <permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/> 添加一個下載任務: ContentValues values = new ContentValues(); values.put(Downloads.URI, url);//指定下載地址 values.put(Downloads.COOKIE_DATA, cookie);//若是下載Server須要cookie,設置cookie values.put(Downloads.VISIBILITY,Downloads.VISIBILITY_HIDDEN);//設置下載提示是否在屏幕頂部顯示 values.put(Downloads.NOTIFICATION_PACKAGE, getPackageName());//設置下載完成以後回調的包名 values.put(Downloads.NOTIFICATION_CLASS, DownloadCompleteReceiver.class.getName());//設置下載完成以後負責接收的Receiver,這個類要繼承BroadcastReceiver values.put(Downloads.DESTINATION,save_path);//設置下載到的路徑,這個須要在Receiver裏自行處理 values.put(Downloads.TITLE,title);//設置下載任務的名稱 this.getContentResolver().insert(Downloads.CONTENT_URI, values);//將其插入到DownloadManager的數據庫中,數據庫會觸發修改事件,啓動下載任務 2:如何爲DownloadManager設置代理,好比Wap values.put(Downloads.PROXY_HOST,"10.0.0.172"); values.put(Downloads.PROXY_PORT,"80"); 3:如何在下載過程當中監聽下載任務 能夠經過監聽數據庫來實現 DownloadsChangeObserver mDownloadObserver=new DownloadsChangeObserver(Downloads.CONTENT_URI); private class DownloadsChangeObserver extends ContentObserver { public DownloadsChangeObserver(Uri uri) { super(new Handler()); } @Override public void onChange(boolean selfChange) { //查詢須要監聽的字段 //好比要監聽實時下載進度,查看當前下載狀態:是否已經斷開,或者下載失敗等等 StringBuilder wherequery = new StringBuilder(Downloads.TITLE); wherequery.append("="); wherequery.append("'"); wherequery.append(mTitle); wherequery.append("'"); mDownloadCursor =mContext.getContentResolver().query(Downloads.CONTENT_URI, new String[] {Downloads.TITLE, Downloads.STATUS, Downloads.CURRENT_BYTES,}, wherequery.toString(), null,orderBy); int mSizeColunmId=mDownloadCursor.getColumnIndexOrThrow(Downloads.CURRENT_BYTES); mDownloadCursor.moveToFirst(); int size=mDownloadCursor.getInt(mSizeColunmId); } } 4:如何刪除下載記錄 private void deleteHistory(String title)//刪除掉指定名稱的下載記錄 { StringBuilder whereDelete = new StringBuilder(Downloads.TITLE); whereDelete.append("="); whereDelete.append("'"); whereDelete.append(str); whereDelete.append("'"); this.getContentResolver().delete(Downloads.CONTENT_URI,whereDelete.toString(), null); }