DownloadManager是Android為開發(fā)者提供的一個后臺應用組件,它通過Http層進行文件的下載任務.
1:使用
首先要在AndroidManifest.xml中申請訪問DownloadManager的權(quán)限
<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,設(shè)置cookie
values.put(Downloads.VISIBILITY,Downloads.VISIBILITY_HIDDEN);//設(shè)置下載提示是否在屏幕頂部顯示
values.put(Downloads.NOTIFICATION_PACKAGE, getPackageName());//設(shè)置下載完成之后回調(diào)的包名
values.put(Downloads.NOTIFICATION_CLASS, DownloadCompleteReceiver.class.getName());//設(shè)置下載完成之后負責接收的Receiver,這個類要繼承 BroadcastReceiver
values.put(Downloads.DESTINATION,save_path);//設(shè)置下載到的路徑,這個需要在Receiver里自行處理
values.put(Downloads.TITLE,title);//設(shè)置下載任務的名稱
this.getContentResolver().insert(Downloads.CONTENT_URI, values);//將其插入到DownloadManager的數(shù)據(jù)庫中,數(shù)據(jù)庫會觸發(fā)修改事件,啟動下載任務
2:如何為DownloadManager設(shè)置代理,比如Wap
values.put(Downloads.PROXY_HOST,"10.0.0.172");
values.put(Downloads.PROXY_PORT,"80");
3:如何在下載過程中監(jiān)聽下載任務
可以通過監(jiān)聽數(shù)據(jù)庫來實現(xiàn)
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) {
//查詢需要監(jiān)聽的字段
//比如要監(jiān)聽實時下載進度,查看當前下載狀態(tài):是否已經(jīng)斷開,或者下載失敗等等
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);
}
https://github.com/commonsguy/cw-android/tree/master/Internet/Downloadhttp://hi-android.info/src/com/android/providers/downloads/DownloadProvider.java.html
posted on 2011-10-29 18:31
小果子 閱讀(1097)
評論(0) 編輯 收藏 引用