Android开发Android知识手机移动程序开发

Android 7.0 调用相机 FileProvider

2017-01-05  本文已影响864人  callxkj

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>

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

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

最后的福利

上一篇 下一篇

猜你喜欢

热点阅读