再安卓7.0谷歌推出了私有文件目录访问权限问题,(我们可以访问到data目录,但是data里面文件访问不到需要申请权限)
安卓apk获取Uri就不能像以前那样方便获取了;
适配方案:
在res新建个xml文件夹,建个file_paths.xml文件 ,文件里面代码如下
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <root-path name="root" path="" /> <files-path name="files" path="" /> <cache-path name="cache" path="" /> <external-path name="external" path="" /> <external-files-path name="external_file_path" path="" /> <external-cache-path name="external_cache_path" path="" /> </paths>
在AndroidMainfest 配置下
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
//8.0安装未知来源权限 <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/> //适配7.0及以上私有目录访问权限问题 <application> <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.android7.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider> </application>
使用代码
Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //7.0私有目录访问限制适配 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); fileUri = android.support.v4.content.FileProvider.getUriForFile(ProjectInit.getApplicationContext(), ProjectInit.getApplicationContext().getPackageName() + ".android7.fileprovider", file); } else { fileUri = Uri.fromFile(file); } intent.setDataAndType(fileUri, "application/vnd.android.package-archive"); ProjectInit.getApplicationContext().startActivity(intent);