Android7.0 FileUriExposedException

来源:互联网 发布:戚薇淘宝店不开了吗 编辑:程序博客网 时间:2024/06/05 20:53

对于面向 Android 7.0 的应用,Android 框架执行的 StrictMode API 政策禁止在您的应用外部公开 file:// URI。如果一项包含文件 URI 的 intent 离开您的应用,则应用出现故障,并出现 FileUriExposedException 异常。
点击查看鸿洋大神解析

适配方案

工具类

public class FileProvider7 {    /**     * 获取文件uri 适配7.0     */    public static Uri getUriForFile(Context context, File file) {        Uri fileUri = null;        if (Build.VERSION.SDK_INT >= 24) {            fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".android7.fileprovider", file);        } else {            fileUri = Uri.fromFile(file);        }        return fileUri;    }    /**     * apk安装适配7.0     */    public static Intent installAPK(Context context, File apkFile) {        Intent installIntent = new Intent(Intent.ACTION_VIEW);        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        setIntentDataAndType(context, installIntent, "application/vnd.android.package-archive", apkFile);        context.startActivity(installIntent);        return installIntent;    }    /**     * apk安装intent适配7.0     */    private static void setIntentDataAndType(Context context, Intent intent, String type, File apkfile) {        intent.setDataAndType(getUriForFile(context, apkfile), type);        if (Build.VERSION.SDK_INT >= 24) {            //添加这一句表示对目标应用临时授权该Uri所代表的文件            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);        }    }}

AndroidManifest.xml配置

<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>

res/xml/file_paths.xml配置

<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>
<root-path/> 代表设备的根目录new File("/");<files-path/> 代表context.getFilesDir()<cache-path/> 代表context.getCacheDir()<external-path/> 代表Environment.getExternalStorageDirectory()<external-files-path>代表context.getExternalFilesDirs()<external-cache-path>代表getExternalCacheDirs()

使用

   Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);   File out = new File(imgPath);   Uri uri = FileProvider7.getUriForFile(activity, out);   imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);   imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);   activity.startActivityForResult(imageCaptureIntent, requestCode);
阅读全文
0 0
原创粉丝点击