Android开发Android技术知识

解决android.os.FileUriExposedExcep

2017-04-25  本文已影响0人  itgoyo简书

今天在使用Android7.0手机升级app的时出现了该问题,然后上StackOverFlow查了一下,找到了几种方法,推荐使用第二种,简单快捷

The app crashes when trying to open a file. It work below Android N, but on Android N it crashes. It only crashes when I try to open a file from the SD card, not from the system partition.

解决方法 ①:

If your targetSdkVersion is 24 or higher, we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.

Steps to replace file:// uri with content:// uri:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
Uri photoURI = Uri.fromFile(createImageFile());

to

Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());

解决方法 ②:

Besides the solution using the FileProvider, there is another way to work around this. use this codes in your project application onCreate();

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure()

May be wrong in the third line

you can run like this:

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.detectFileUriExposure();
        }

StackOverFlow:
http://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed

上一篇 下一篇

猜你喜欢

热点阅读