Android開發 DownloadManager詳解
阿新 • • 發佈:2020-07-14
前言
此部落格正在整理中。。。
參考:https://www.jianshu.com/p/e0496200769c
程式碼
請求
DownloadManager downloadManager = (DownloadManager) MainActivity.this.getApplication().getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://dl.hdslb.com/mobile/latest/iBiliPlayer-html5_app_bili.apk")); request.setDestinationInExternalPublicDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath(),"iBiliPlayer-html5_app_bili.apk"); request.setTitle("測試下載");//設定標題 request.setDescription("下載中");//設定描述 request.addRequestHeader("token","11");//新增頭 key: value request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);//設定網路型別 request.setVisibleInDownloadsUi(false);//是否顯示下載 從Android Q開始會被忽略 // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);//僅在下載中時顯示在通知中,完成後會自動隱藏 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//下載中與下載完成後都會在通知中顯示 id = downloadManager.enqueue(request);//加入佇列,會返回一個唯一下載id
查詢
private void queryFileName(long id){ DownloadManager downloadManager = (DownloadManager) MainActivity.this.getApplication().getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(id); Cursor cursor = downloadManager.query(query); if (cursor.moveToFirst()) { String file = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI)); Log.e("除錯_臨時_log", "this_" + file); } }
監聽
AppDownReceiver appDownReceiver = new AppDownReceiver(); registerReceiver(appDownReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
class AppDownReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); Log.e("除錯_臨時_log", "this_ id = " + completeDownloadId); DownloadManager downloadManager = (DownloadManager) context.getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = downloadManager.getUriForDownloadedFile(completeDownloadId); installApk(context, uri); } private void installApk(Context context, Uri uri) { Intent intent = new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(uri, "application/vnd.android.package-archive"); } else { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(uri, "application/vnd.android.package-archive"); } context.startActivity(intent); } }