美文网首页安卓
android 7.0系统解决拍照的问题android.os.F

android 7.0系统解决拍照的问题android.os.F

作者: 流水潺湲 | 来源:发表于2018-04-04 09:56 被阅读131次

概述

之前项目的新特性适配工作都是同事在做,一直没有怎么太关注,不过类似这些适配的工作还是有必要做一些记录的。

对于Android 7.0,提供了非常多的变化,详细的可以阅读官方文档Android 7.0 行为变更,记得当时做了多窗口支持、FileProvider以及7.1的3D Touch的支持,不过和我们开发者关联最大的,或者说必须要适配的就是去除项目中传递file://类似格式的uri了。

在官方7.0的以上的系统中,尝试传递 file://URI可能会触发FileUriExposedException

使用FileProvider兼容拍照

其实对于如何使用FileProvider,其实在FileProvider的API页面也有详细的步骤,有兴趣的可以看下。

https://developer.android.com/reference/android/support/v4/content/FileProvider.html

FileProvider实际上是ContentProvider的一个子类,它的作用也比较明显了,file:///Uri不给用,那么换个Uri为content://来替代。

在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()

每个节点都支持两个属性:

name
path

方法一:

解决Android N文件访问crash android.os.FileUriExposedException file:///storage/emulated/0/xxx

原因:

Android N对访问文件权限收回,按照Android N的要求,若要在应用间共享文件,您应发送一项 content://URI,并授予 URI 临时访问权限。
而进行此授权的最简单方式是使用 FileProvider类。
1.在mainfest中加入FileProvider注册

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

2.配置filepaths文件

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

其中:

files-path代表的根目录: Context.getFilesDir()
external-path代表的根目录: Environment.getExternalStorageDirectory()
cache-path代表的根目录: getCacheDir()

<external-path path="honjane/" name="files_path" />

path 代表要共享的目录
name 只是一个标示,随便取吧 自己看的懂就ok

for example:通过provider获取到的uri链接

content://com.ys.providerdemo.fileprovider/files_path/files/b7d4b092822.pdf

name对应到链接中的files_path

path对应到链接中的 files ,当然files是在ys/目录下
3.访问文件

/**
     * 打开文件
     * 当手机中没有一个app可以打开file时会抛ActivityNotFoundException
     * @param context     activity
     * @param file        File
     * @param contentType 文件类型如:文本(text/html)     
     */
    public static void startActionFile(Context context, File file, String contentType) throws ActivityNotFoundException {
        if (context == null) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setDataAndType(getUriForFile(context, file), contentType);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    /**
     * 打开相机
     *
     * @param activity    Activity
     * @param file        File
     * @param requestCode result requestCode
     */
    public static void startActionCapture(Activity activity, File file, int requestCode) {
        if (activity == null) {
            return;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getUriForFile(activity, file));
        activity.startActivityForResult(intent, requestCode);
    }

    private static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), "你的应用名.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }

同样访问相机相册都通过FileProvider.getUriForFile申请临时共享空间
已写成工具类上传到github,需要直接下载
使用方法简单,一行代码搞定

打开文件:

 try {
      FileUtils.startActionFile(this,path,mContentType);
    }catch (ActivityNotFoundException e){

 }

调用相机:

 FileUtils.startActionCapture(this, file, requestCode);

修复bug:

Java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/xxx/xxx/file/12b31d2cab6ed.pdf

external与storage/emulated/0/对应,乍一看貌似没什么问题,path设置的是external的根路径,对应Environment.getExternalStorageDirectory(),

然而这个方法所获取的只是内置SD卡的路径,所以当选择的相册中的图片是外置SD卡的时候,就查找不到图片地址了,因此便抛出了failed to find configured root that contains的错误。

通过分析FileProvider源码发现,在xml解析到对应的标签后,会执行 buildPath() 方法来将根标签(files-path,cache-path,external-path等)对应的路径作为文件根路径,

在buildPath(),会根据一些常量判断是构建哪个目录下的path,除了上面介绍的几种path外还有个TAG_ROOT_PATH = “root-path” ,只有当不是root-path时才会去构建其他path,

官方也没介绍这个root-path,测试了一下发现对应的是DEVICE_ROOT指向的整个存储的根路径,这个bug就修复了

修改filepaths文件:

<paths>
      <root-path name="honjane" path="" />
</paths>

方法二:(没试过,网上搜的)

除了解决方案之外FileProvider,还有另一种解决方法。简单的说

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

Application.onCreate()。以这种方式,VM会忽略文件URI曝光。

方法

builder.detectFileUriExposure()

启用文件曝光检查,如果我们没有设置VmPolicy,这也是默认行为。

我遇到一个问题,如果我使用a content:// URI发送东西,一些应用程序是无法理解的。并且不允许降级target SDK版本。在这种情况下,我的解决方案是有用的。







补充:

别以为上述过程解决了,比如打开相册,不可能只有一个地方的路径,就需要在files_path.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>

使用FileProvider API

比如相机拍照:
好了,接下来就可以通过FileProvider把我们的file转化为content://uri了~

public void takePhotoNoCompress(View view) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

            String filename = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA)
                    .format(new Date()) + ".png";
            File file = new File(Environment.getExternalStorageDirectory(), filename);
            mCurrentPhotoPath = file.getAbsolutePath();

            Uri fileUri = FileProvider.getUriForFile(this, "com.zhy.android7.fileprovider", file);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO);
        }
    }

核心代码就这一行了~

FileProvider.getUriForFile(this, "com.zhy.android7.fileprovider", file);

现在拿7.0的原生手机运行就正常啦~

不过事情到此并没有结束~~

打开一个其他8.0手机,运行上述代码,你会发现又Crash啦,抛出了:Permission Denial~

java.lang.SecurityException: Permission Denial: 
opening provider android.support.v4.content.FileProvider 
        from ProcessRecord{18570a 27107:com.google.android.packageinstaller/u0a26} (pid=27107, 
uid=10026) that is not exported from UID 1000

对于权限,还提供了一种方式,即:

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

还有低版本兼容性适配:
这样就搞定了,不过还是挺麻烦的,如果你仅仅是对旧系统做兼容,还是建议做一下版本校验即可,也就是说不要管什么授权了,直接这样获取uri

Uri fileUri = null;
if (Build.VERSION.SDK_INT >= 24) {
    fileUri = FileProvider.getUriForFile(this, "com.zhy.android7.fileprovider", file);
} else {
    fileUri = Uri.fromFile(file);
}

快速完成适配

(1)新建一个module

创建一个library的module,在其AndroidManifest.xml中完成FileProvider的注册,代码编写为:

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

注意一点,android:authorities不要写死,因为该library最终可能会让多个项目引用,而android:authorities是不可以重复的,如果两个app中定义了相同的,则后者无法安装到手机中(authority conflict)。

同样的的编写file_paths~

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

最后再编写一个辅助类,例如:

public class FileProvider7 {

    public static Uri getUriForFile(Context context, File file) {
        Uri fileUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            fileUri = getUriForFile24(context, file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }

    public static Uri getUriForFile24(Context context, File file) {
        Uri fileUri = android.support.v4.content.FileProvider.getUriForFile(context,
                context.getPackageName() + ".android7.fileprovider",
                file);
        return fileUri;
    }

    public static void setIntentDataAndType(Context context,
                                            Intent intent,
                                            String type,
                                            File file,
                                            boolean writeAble) {
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setDataAndType(getUriForFile(context, file), type);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (writeAble) {
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        } else {
            intent.setDataAndType(Uri.fromFile(file), type);
        }
    }
}

可以根据自己的需求添加方法。

好了,这样我们的一个小库就写好了~~

(2)使用

如果哪个项目需要适配7.0,那么只需要这样引用这个库,然后只需要改动一行代码即可完成适配啦,例如:

拍照

public void takePhotoNoCompress(View view) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        String filename = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA)
                .format(new Date()) + ".png";
        File file = new File(Environment.getExternalStorageDirectory(), filename);
        mCurrentPhotoPath = file.getAbsolutePath();

        Uri fileUri = FileProvider7.getUriForFile(this, file);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO);
    }
}

只需要改动

 Uri fileUri = FileProvider7.getUriForFile(this, file);

即可。

安装apk

同样的修改setDataAndType为:

FileProvider7.setIntentDataAndType(this,
      intent, "application/vnd.android.package-archive", file, true);

即可。

ok,繁琐的重复性操作终于简化为一行代码啦~

参考:

安装APP的时候:Android应用更新-自动检测版本及自动升级

相关文章

网友评论

    本文标题:android 7.0系统解决拍照的问题android.os.F

    本文链接:https://www.haomeiwen.com/subject/qozhhftx.html