Android 7.0 调用相机 FileProvider

作者: callxkj | 来源:发表于2017-01-05 17:14 被阅读864次

FileProvider-相机相册

最好的参考是google官网

一共有以下几个步骤

1.在manifest中添加provider

<provider
            android:authorities="com.mydemo.fileprovider"
            android:name="android.support.v4.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true"
            >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"
                />
        </provider>
  • authorities 类似schema,命名空间之类,后面会用到
  • name v4包中的fileprovider
  • exported false表示我们的provider不需要对外开放。
  • grantUriPermissions 申明为true,你才能获取临时共享权限。
  • resource 名字随便跟第二步有关

2.在resourse下面新建xml文件夹,然后命名为第一步中resource中的文件名字

  • 例如file_paths 的代码如下
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-cache-path name="images" path="Pictures/"/>
</paths>
  • name 可以谁便填写用来隐藏暴露出去的文件夹名字,其他应用用name后面的名字来访问
  • path 表示当前文件夹下面的所有文件都可以共享,
  • 一定要注意Pictures后面有个"/""

  • paths标签下面的元素必须是以下的一种或者几种
<files-path name="name" path="path" />
对应的文件夹是 Context.getFilesDir().
<cache-path name="name" path="path" />
对应的文件夹是 getCacheDir().
<external-path name="name" path="path" />
对应的文件夹是 Environment.getExternalStorageDirectory().
<external-files-path name="name" path="path" />
对应的文件夹是 Context.getExternalFilesDir(null).
<external-cache-path name="name" path="path" />
对应的文件夹是 Context.getExternalCacheDir().

3.简单的拍照获取照片(先要申请权限sd卡与相机权限)

// 这里的getExternalCacheDir() 与 xml中external-cache-path 相对应 
        File imagePath = new File(getExternalCacheDir(), "Pictures");
        if (!imagePath.exists()){imagePath.mkdirs();}
        File newFile = new File(imagePath, "mycamera.jpg");
//    com.mydemo.fileprovider 为manifest重配置的 domain
        Uri contentUri = FileProvider.getUriForFile(this,
                "com.mydemo.fileprovider", newFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        startActivityForResult(intent, 100);

4.总结

主要是通过fileprovider把file:/// Uri 替换成content:// Uri

最后的福利

相关文章

网友评论

    本文标题:Android 7.0 调用相机 FileProvider

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