本文系转载,原文地址:https://www.cnblogs.com/sushine/p/9300361.html
安卓:7.0及以上通过FileProvider读取文件和完成更新
最近在做app的自动更新功能,在网上找了别人做好的demo【感谢crazyfzw的分享】,在测试机[4.4,5.0,6.0]上能正常使用,本来就打算这么放过了。结果在别人的手机上出现了无法自动安装的情况:下载完文件后不能发起调用。 发现他们使用的系统是7.0或8.0,百度后才知道高版本的系统对共享目录和未知来源的安装文件做了限制。
一般的自动更新功能,是通过解析服务器上记录的版本信息【如json文件】,获取版本号和本地进行对比,再进行下载 和调用文件、完成安装。
在7.0中,需要使用FileProvider。
1. 在AndroidManifest.xml中,申请权限:
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="com.name.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
2. 在xml目录(如果没有xml目录,就在res下面新建一个xml目录)下新建file_paths,指定路径:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="apkname"/>
</paths>
3.在下载文件的线程中:
//指定目录
String mSavePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "apkname" +File.separator;
File dir = new File(mSavePath);
String apkName = urlStr.substring(urlStr.lastIndexOf("/") + 1, urlStr.length());//根据json,取得apK文件名
File apkFile = new File(dir, apkName);
4. 下载完成后调用installApk(apkFile),对版本号进行判断. 通过日志输出发现,7.0及以上获取的地址是file开头的,而7.0以下版本获取的地址是context开头的路径。 最开始修改后更新,出现”解析包错误“的提示,连接电脑看logcat发现,原来是apkUri和msavepath不一致。修改后就可以了。
if(Build.VERSION.SDK_INT>=24){ Log.e(TAG,"Version>=24"); Uri apkUri = FileProvider.getUriForFile(this, "与AndroidManifest中的android:authorities一致", apkFile); Log.e(TAG,apkUri.toString()); Log.e(TAG,apkFile.getAbsolutePath()); Intent install = new Intent(Intent.ACTION_VIEW); install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); install.setDataAndType(apkUri, "application/vnd.android.package-archive"); startActivity(install); } else{ //如果没有设置SDCard写权限,或者没有sdcard,apk文件保存在内存中,需要授予权限才能安装 Log.e(TAG,"Version<=24"); try { String[] command = {"chmod", "777", apkFile.toString()}; //777代表权限 rwxrwxrwx ProcessBuilder builder = new ProcessBuilder(command); builder.start(); } catch (IOException ignored) { } intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); }
5. 对于安卓8.0,增加了对”未知来源应用“的安装限制,每次都需要申请权限。 不知道是不是因为我有对应用进行签名的关系,8.0没有申请权限,也能完成安装