亲测有用,原文下载地址:
原文地址:https://blog.csdn.net/weixin_36554045/article/details/79108796
下面是原文:
创建一个广播类
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中去注册广播
最后就是我们的下载方法
1.下载APP更新时
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.下载其他文件时
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);}