适配Android7.0的拍照问题可直接使用!

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_37758967/article/details/82909669

最近在项目遇到拍照上传的功能,才知道Android7.0之后直接使用本地真实路径的Uri会抛出FileExposedExceptiond 异常。

才知道7.0之后需要用FileProvider才行。找了网上很多都不能用!

直接上代码吧

第一步,在AndroidMainfest里加上

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example.administrator.myapplication.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">

    <!--指定Uri的共享路径-->
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths" />
</provider>

第二步创建xml文件夹,并创建provider_paths资源文件

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_image" path="."/>
</paths>

在activity中启动相机,直接在button里调用takephone()方法就可以

private static  final int TAKE_PHONE=20;//启动相机码
private File outputImage
private Uri imageUri;
private void takePhone() {
    //创建一个File对象用于存储拍照后的照片
     outputImage=new File(getExternalCacheDir(),"one_image.png");
    try{
        if(outputImage.exists()){
            outputImage.delete();
        }
        outputImage.createNewFile();
    }catch (Exception e){
        e.printStackTrace();
    }

    //判断Android版本是否是Android7.0以上
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
        imageUri= FileProvider.getUriForFile(MainActivity.this,"com.example.administrator.myapplication.fileprovider",outputImage);
//AndroidMainfest中authorities一定要跟第二个参数一样!
    }else{
        imageUri=Uri.fromFile(outputImage);
    }

    //启动相机程序
    Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
    intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
    startActivityForResult(intent,TAKE_PHONE);
}
在onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode){
        case TAKE_PHONE:
            //相机拍照回调
            if(resultCode==RESULT_OK){

                Log.i("okokok",imageUri.getPath());//可以打印出路径,转为Bitmap显示

            }

    }


}

如果要上传到服务器的话,拍照完直接拿outputImage上传就可以,虽然是1.5m的文件没压缩。

如果有说的不好的麻烦各位大佬指出来谢谢!!

扫描二维码关注公众号,回复: 7206914 查看本文章

版权声明:本文为博主原创文章,未经博主允许不得转载https://blog.csdn.net/weixin_37758967/article/details/82909669

猜你喜欢

转载自blog.csdn.net/weixin_37758967/article/details/82909669