摘要:本文分享了Android开发源码中APK适配方法,
首先看一下安装apk文件的代码
/**
* 通过隐式意图调用系统安装程序安装APK */ public static void install(Context context) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile( new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "xxxx.apk")), "application/vnd.android.package-archive"); context.startActivity(intent); } 测试发现该段代码在7.0一下的机型上可以成功打开指定路径下的指定apk文件 , 但是在7.0+的机型上调用该代码会报错: android.os.FileUriExposedException: file:///storage/emulated/0/Download/xxxx.apk exposed beyond app through Intent.getData() 原因在于:Android 7.0 版本开始 禁止向你的应用外公开 file:// URI。 如果一项包含文件 file:// URI类型 的 Intent 离开你的应用,应用失败,并出现 FileUriExposedException 异常。 解决方法: 一、在AndroidManifest.xml 文件中添加 四大组件之一的 <provider< p=""> android:name="android.support.v4.content.FileProvider" android:authorities="com.xxx.xxxx.fileprovider" android:grantUriPermissions="true" android:exported="false"> <meta-data< p=""> <meta-data< p="" style="color: rgb(51, 51, 51); font-family: Simsun; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(249, 249, 249);"><meta-data< p=""> android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
注意这里的 android :authorities 属性的值 中的 com.xxx.xxxx 是你的包名,不可随意填写
二、res 目录下 建一个xml 文件,并新建xml文件file_paths.xml
注意文件名要和第一步中的 resource 属性的值一致
内容为:
"1.0" encoding="utf-8"?> "." name="download"/> 三、根据机型的Android系统级别执行不同的安装apk的代码 注意,根据系统版本执行不同代码,7.0以下调用7.0+的代码会报错,7.0+的调用7.0以下的会报错。 if (file!=null){ // file 即 apk文件 Intent intent = new Intent(Intent.ACTION_VIEW); // 由于没有在Activity环境下启动Activity,设置下面的标签 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上 Uri apkUri = FileProvider.getUriForFile(context, "com.xxx.xxxxx.fileprovider", file); //添加这一句表示对目标应用临时授权该Uri所代表的文件 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(apkUri, "application/vnd.android.package-archive"); }else{ intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); } context.startActivity(intent); }
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号