Android7.0及以上 拍照crash问题

版权声明:本文为博主原创文章,转载需注明博主文章链接。 https://blog.csdn.net/black_bread/article/details/69257748

网上很多教程都说使用FileProvider,就是没有一个测试成功的,都是报错,无奈。。。

1.添加权限

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>


2.在AndroidManifest.xml中配置provider

*** android:authorities随意都行,最好是包名,后面会用到

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example.android.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths"></meta-data>
</provider>

3.在res/xml下新建file_paths.xml文件

*** name属性可随意,path指定保存图片的路径

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>


4.代码创建保存图片的File

*** File的路径最好是getExternalFilesDir() or getFilesDir(),这样app被卸载,这两个文件路径也会被删除

/**
 * 创建用于保存图片File
 */
private File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(imageFileName, ".jpg", storageDir);
    return image;
}

5.开启拍照功能

*** 最好在执行startActivityForResult()方法之前调用intent.resolveActivity方法检查。执行检查是很重要的,因为如果startActivityForResult()没有可以响应的对象,应用程序会崩溃(crash)。

*** getUriForFile方法第二个参数要与AndroidManifest.xml中配置的provider的主机名一致

static final int REQUEST_TAKE_PHOTO = 1;

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this, "com.example.android.fileprovider", photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

6.demo

链接:https://github.com/yinhuagithub/Demo_TakePhoto


7.FileProvider

参考之前文章:http://blog.csdn.net/black_bread/article/details/69258613

猜你喜欢

转载自blog.csdn.net/black_bread/article/details/69257748