您的位置:首页 > 移动开发 > Android开发

Android7.0适配SD卡权限

2018-07-12 16:52 609 查看
之前APP中有一个功能,版本更新下载新的APK文件之后,直接打开系统的安装页面。原来的代码如下:

private void install(File apkFile) {
Uri uri = Uri.fromFile(apkFile);
Intent localIntent = new Intent(Intent.ACTION_VIEW);
localIntent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(localIntent);
}

以上的代码在7.0一下正常执行,但是运行在7.0以上的设备就会闪退。而7.0的” StrictMode API 政策” 禁止向你的应用外公开 http://my.oschina.net/simaben/blog/file:/URI。 如果一项包含文件 http://my.oschina.net/simaben/blog/file:/URI类型 的 Intent 离开你的应用,应用失败,并出现 FileUriExposedException 异常。解决办法如下:

在res目录下新建一个xml文件夹,并创建一个名为provider_paths.xml的文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_path"
path="."/>
</paths>


在manifest文件的application标签下添加一个provider标签

<application>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="包名.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>

其中特别要注意android:authorities,需要使用包名.fileprovider的方式。
3. 修改install方法

public static void install(Context ctx, File apkfile) {
if (apkfile == null) return;
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
String authority = ctx.getPackageName() + ".fileprovider";
Uri contentUri = FileProvider.getUriForFile(ctx, authority, apkfile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android" +
".package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
ctx.startActivity(intent);
}

要注意authority的值必须和provider标签中的android:authorities一模一样,否则会报错。
这样就解决了7.0上SD卡权限报错问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ActionView Android