问题如标题
想用浏览器下载,或者下载器下载
应用场景有以下几种:
1.监控DownloadManager,文件下载完成时以文件路径的形式发送intent:
// install work
Intent install = new Intent(Intent.ACTION_VIEW);
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String filePath = "file://" +
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" +urlMap.get(String.valueOf(downloadId));
install.setDataAndType(Uri.parse(filePath),"application/vnd.android.package-archive");
startActivity(install);
关键就是这里:
promptInstall.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/myApp.apk")),
"application/vnd.android.package-archive");
需要设置mimeType为”application/vnd.android.package-archive”
————————————————————————————————
2.形式:DownloadManager添加之初就指定该下载文件为APK文件,方法如下:(因为项目需求,并不能使Activity保持在内存中,无法注册BroadcastReceiver监控下载管理器)
(关于下载管理器的使用办法,中文教程看这里(较繁琐,不推荐))更清晰的英文教程
// parse url
Uri mUri = Uri.parse(url);
// create request
DownloadManager.Request r = new DownloadManager.Request(mUri);
// set request property
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "YourApkName.apk");
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// create manager
DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
// key code, set mine type
r.setMimeType("application/vnd.android.package-archive");
// add to queue
dm.enqueue(r);
其核心也就是设置DownloadManager的request的mimeType为”application/vnd.android.package-archive”;
这样设置之后,打开下载的APK就不会报“无法打开文件”的错误了;