7.0权限处理

来源:互联网 发布:淘宝app里面是h5吗 编辑:程序博客网 时间:2024/06/08 08:19

一、在7.0系统上,版本更新后安装APP时,出现android.os.FileUriExposedException: 异常
解决方案:
1、在在AndroidManifest.xml中的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/file_provider" /> </provider>

这里:
grantUriPermissions:必须是true,表示授予 URI 临时访问权限
exported:必须是false
resource:中的@xml/file_paths是我们接下来要添加的文件
authorities:你的包名 + “.fileProvider”

2、在res目录下新建一个xml文件夹,并且新建一个file_provider的xml文件

<?xml version="1.0" encoding="utf-8"?><paths >    <!--1、对应内部内存卡根目录:Context.getFileDir()-->    <!--<files-path-->        <!--name="int_root"-->        <!--path="/" />-->    <!--2、对应应用默认缓存根目录:Context.getCacheDir()-->    <!--<cache-path-->        <!--name="app_cache"-->        <!--path="/" />-->    <!--3、对应外部内存卡根目录:Environment.getExternalStorageDirectory()-->    <!--<external-path-->        <!--name="ext_root"-->        <!--path="pictures/" />-->    <!--4、对应外部内存卡根目录下的APP公共目录:Context.getExternalFileDir(String)-->    <!--<external-files-path-->        <!--name="ext_pub"-->        <!--path="/" />-->    <!--5、对应外部内存卡根目录下的APP缓存目录:Context.getExternalCacheDir()-->    <!--<external-cache-path-->        <!--name="ext_cache"-->        <!--path="/" />-->    <external-path path="Android/data/com.lckj.eight/" name="files_root" />    <external-path path="." name="external_storage_root" /></paths>

path:需要临时授权访问的路径(.代表所有路径)
name:就是你给这个访问路径起个名字,没啥鸟用,用来隐藏真实文件目录

3、以前,Uri的获取方式是以file://xxx的样式来,那么我们也就是通过Uri.fromFile()来获取。在7.0系统上需要发送一项content://URI,并授予 URI 临时访问权限。进行此授权的最简单方式是使用FileProvider类。

  //判断是否是AndroidN以及更高的版本 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {     intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);             Uri contentUri = FileProvider.getUriForFile(context, MyApplication.getContext().getPackageName() + ".fileProvider", filePath));     intent.setDataAndType(contentUri, "application/vnd.android.package-archive");} else {    intent.setDataAndType(filePath, "application/vnd.android.package-archive");    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);}startActivity(intent);

这里需要注意的是:
AndroidManifest.xml处的android:authorities跟mActivity.getPackageName() + “.fileProvider”不一样会报:
Attempt to invoke virtual method ‘android.content.res.XmlResourceParser android.content.pm.
PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)’ on a null object reference异常

二、在7.0系统上获取getDeviceId()时需要先获取Manifest.permission.READ_PHONE_STATE)权限,不然也会抛出异常