调用系统方法升级更新、兼容7.0和8.0
一、先不多说,上核心代码。
/** * 调用系统安装,兼容Android7.0以上 * 必须具有读写权限 * @param filePath 完整路径,包括后缀名 * @param authority 临时授权口令 */ @RequiresPermission(anyOf = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}) private void install(Context mContext,String filePath,String authority){ if(filePath == null || mContext == null)return; File apkFile = new File(filePath); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri = null; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); uri = FileProvider.getUriForFile(mContext,authority,apkFile); }else{ uri = Uri.fromFile(apkFile); } intent.setDataAndType(uri,"application/vnd.android.package-archive"); mContext.startActivity(intent); }
对于上面的代码需要注意的是authority这个参数,在Android N后由于Google收紧权限的问题,所以需要提供Provider才能访问文件。而其中比较关键的是android:authorities这个属性(下面会介绍到),它的值就是authority这个参数的值,可以随便填,但一般都是使用:包名+“.fileprovider”这样的形式。
二、所需权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
注意:如果缺少访问存储的权限,可能会导致:解析包时出现异常,所以这些权限不可缺少。(╥╯^╰╥)本人就因为漏了这个弄了好久......,当然出现“解析包时出现异常”的其他原因还有其他可能,如下载不完整或出错、文件路径不正确等原因,请逐一排查。
三、AndroidManifest.xml配置
<provider android:authorities="随便写,但这个值就是上面按照方法中authority参数的值" android:name="android.support.v4.content.FileProvider" android:exported="false" android:grantUriPermissions="true" > <!--android:authorities的值可以随便写,但一般为:包名+".fileprovider"--> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
3.1、file_paths的详细内容
<?xml version="1.0" encoding="utf-8"?> <paths> <external-path name="JniStudy" path="." /> <!-- 不是很明白name的作用,随便写什么都行;path不可随便写,一般为.或者/ --> </paths>
可参考:Android 7.0适配-应用之间共享文件(FileProvider)
结束!!!!!!!