親測有用,原文下載地址:android
原文地址:https://blog.csdn.net/weixin_36554045/article/details/79108796app
下面是原文:url
建立一個廣播類.net
public class UpdataBroadcastReceiver extends BroadcastReceiver { @SuppressLint("NewApi") public void onReceive(Context context, Intent intent) { long myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); SharedPreferences sPreferences = context.getSharedPreferences("downloadcomplete", 0); long refernece = sPreferences.getLong("refernece", 0); if (refernece == myDwonloadID) { String serviceString = Context.DOWNLOAD_SERVICE; DownloadManager dManager = (DownloadManager) context.getSystemService(serviceString); Intent install = new Intent(Intent.ACTION_VIEW); Uri downloadFileUri = dManager.getUriForDownloadedFile(myDwonloadID); install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive"); install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(install); } } }
在AndroidManifest.xml中去註冊廣播xml
<receiver android:name=".updata.UpdataBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.DOWNLOAD_COMPLETE" /> </intent-filter> </receiver>
最後就是咱們的下載方法blog
1.下載APP更新時ip
private void downloadAPK(String url) { DownloadManager dManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse(url); DownloadManager.Request request = new DownloadManager.Request(uri); // 設置下載路徑和文件名 request.setDestinationInExternalPublicDir("xxx(路徑)", "xxx.apk"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setMimeType("application/vnd.android.package-archive"); // 設置爲可被媒體掃描器找到 request.allowScanningByMediaScanner(); // 設置爲可見和可管理 request.setVisibleInDownloadsUi(true); long refernece = dManager.enqueue(request); // 把當前下載的ID保存起來 SharedPreferences sPreferences = getSharedPreferences("downloadcomplete", 0); sPreferences.edit().putLong("refernece", refernece).commit(); }
2.下載其餘文件時get
private void imageDownload(String downloadUrl) { DownloadManager dManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse(downloadUrl); DownloadManager.Request request = new DownloadManager.Request(uri); String[] urlname = downloadUrl.split("/"); // 設置下載路徑和文件名 request.setDestinationInExternalPublicDir("xxx(路徑)", urlname[urlname.length - 1]); // request.setDescription("DOTA2資料庫新版本下載"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //request.setMimeType("application/vnd.android.package-archive"); // 設置爲可被媒體掃描器找到 request.allowScanningByMediaScanner(); // 設置爲可見和可管理 request.setVisibleInDownloadsUi(true); long refernece = dManager.enqueue(request); }