android studio 7.0 FileProvider问题详解及相机示例

自从Android版本升级到7.0(sdk24)以后,很多人发现以往的拍照逻辑在新手机上会报错了,百思不得其解之际,在网上一搜,原来是Android官方为了安全需要,屏蔽了app之间进行数据访问的接口;并且官方也给出了一套对应的解决办法:就是FileProvider。

下面我们就来看看File Provider的用法:

 1.因为FileProvider是Provider的子类,所以首先需要在mainfest文件中定义一个FileProvider,或者自定义一个CustomFileProvider继承FileProvider,具体代码参考:
<application>
     <provider  android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
   <meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
        </provider>
    </application>
authorities为自定义字符串,什么都可以,后面需要用到;
exported:此字段设置为false,意思是不需要向外公开;
grantUriPermissions:设为true,给与访问file的权限;
metadata中的xml为自定义的xml文件,下面介绍
  1. 指定xml文件,就是上面的xml/file_paths文件:
    此步需要在res文件下下另创建一个xml的文件夹,然后在此文件夹下定义一个自定义的xml文件,内部代码如下:
<paths  xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="my_images" path="images/"/>
</paths>
<paths>元素下面必须下面的一种或几种:
<files-path name="name" path="path" />
        对应:Context.getFilesDir().
<external-path name="name" path="path" />
        对应:Context.getExternalFilesDir()
<cache-path name="name" path="path" />
        对应:Context.getCacheDir()
            其中path是你需要分享的文件所在的子路径,而name是你为了隐藏真实路径而虚拟的一个路径名字

上面两步基本配置已经完成了,下面用相机的例子来说明:
先放代码:

Intent intent = new Intent();        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
newFile=new File(Environment.getExternalStorageDirectory(), "/camera_path/"+System.currentTimeMillis() + ".jpg");
if (!newFile.getParentFile().exists()){
newFile.getParentFile().mkdirs();
}
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
contentUri = FileProvider.getUriForFile(MainActivity.this,
                    "com.mydomain.fileprovider", newFile);
}else{
   contentUri = Uri.fromFile(newFile);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(intent, Config.CAMERA_REQUESTCODE);

首先需要给intent添加访问URI的临时访问权限,可以用read或者write或者两者都有;
然后判断当前的Android版本是不是7.0,如果高于7.0,则需要用MyFileProvider.getUriForFile(MainActivity.this,
“com.mydomain.fileprovider”, newFile);来定义contentUri,此返回的uri为content://类型;
如果是在7.0以下,则用老方法Uri.fromFile(newFile)此返回的是file://类型,然后在onActivityResult()方法中:根据contentUri处理不同的逻辑操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值