In a recent project encountered camera upload function, only after Android7.0 directly using the local real path of Uri will throw FileExposedExceptiond
an exception.
You need to know the job with FileProvider after 7.0. Do not use the Internet to find a lot!
Directly on the bar code
The first step in adding the 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>
The second step to create xml folder and create a resource file 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>
To activate the camera in activity, call takephone directly on the button in () method can be
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显示
}
}
}
If you want to upload to the server, then get finished pictures can be uploaded directly outputImage, although 1.5m file is not compressed.
If you have trouble saying good big brother pointed out to you thank you! !
Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allow https://blog.csdn.net/weixin_37758967/article/details/82909669