android 之 DownloadManager

基礎使用:

DownloadManager.Request request;
try{
    request = new DownloadManager.Request(Uri.parse("String url"));
    // 放入下載隊列
    Context appContext = getApplicationContext();
    DownloadManager manager = (DownloadManager)appContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}catch (Exception e){
    e.printStackTrace();
    return;
}

加入下載隊列後能夠得到一個下載ID用於建立下載進度觀察者或者下載完成的廣播通知android

long downloadId = manager.enqueue(request);

下載進度觀察者:

final DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, new ContentObserver(new Handler()) {
    @Override
    public void onChange(boolean selfChange) {
        int[] bytesAndStatus = new int[]{-1, -1, 0};
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = null;
        try {
            cursor = dm.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                //已經下載文件大小
                bytesAndStatus[0] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //下載文件的總大小
                bytesAndStatus[1] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //下載狀態
                bytesAndStatus[2] = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                //計算下載進度
                float progress = (float)bytesAndStatus[0]/bytesAndStatus[1];
                
                // 當進度徹底執行好了記得 註銷觀察者 不註銷的話 可能會多跑幾回
                if(progress == 1){
                    getContentResolver().unregisterContentObserver(this);
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
});

註冊廣播接收者

IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        if (ID == downloadId) {
            // 執行完成後的代碼
            Toast.makeText(getApplicationContext(), "任務:" + downloadId + " 下載完成!", Toast.LENGTH_LONG).show();
            // 記得註銷廣播接收者  不註銷的話這個會一直在的
            unregisterReceiver(this);
        }
    }
};
registerReceiver(broadcastReceiver, intentFilter);

其餘:

1.保存路徑問題app

request.setDestinationInExternalPublicDir("保存路徑","保存的文件名稱");

2.通知欄顯示下載信息ide

request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setTitle("下載");
request.setDescription("應用正在下載");
request.setAllowedOverRoaming(false);

3.我的使用目的:下載apk,完成後調用安裝this

String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager dManager = (DownloadManager) context.getSystemService(serviceString);
// 根據下載管理獲取下載文件的URI 本身寫Uri.pase("文件路徑")也是能夠的
Uri downloadFileUri = dManager.getUriForDownloadedFile(downloadId);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 該語句會授予臨時的訪問權限 不然會秒退
intent.setDataAndType(fileuri, "application/vnd.android.package-archive");
startActivity(intent);
相關文章
相關標籤/搜索