1.manifest
<!-- 这里如果使用是v4包将android:name 的路径改为android.support.v4.content.FileProvider 就好了 -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
2.res/xml/file_paths
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!-- xml文件是唯一设置分享的目录 ,不能用代码设置
1.<files-path> getFilesDir() /data/data//files目录
2.<cache-path> getCacheDir() /data/data//cache目录
3.<external-path> Environment.getExternalStorageDirectory()
SDCard/Android/data/你的应用的包名/files/ 目录
4.<external-files-path> Context#getExternalFilesDir(String) Context.getExternalFilesDir(null).
5.<external-cache-path> Context.getExternalCacheDir().
-->
<!-- path :代表设置的目录下一级目录 eg:<external-path path="images/"
整个目录为Environment.getExternalStorageDirectory()+"/images/"
name: 代表定义在Content中的字段 eg:name = "myimages" ,并且请求的内容的文件名为default_image.jpg
则 返回一个URI content://com.example.myapp.fileprovider/myimages/default_image.jpg
-->
<!--当path 为空时 5个全配置就可以解决-->
<!--下载apk-->
<external-path path="."
name="sdcard_files" />
<!--相机相册裁剪-->
<external-files-path
path="file/" name="camera_has_sdcard"/>
<files-path path="."
name="camera_no_sdcard"/>
</paths>
- 实现代码
//返回图片路径
public static String takePhoto(Activity context, int request) {
String filePath = null;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
//创建图片文件
photoFile = createImageFile();
filePath = photoFile.getAbsolutePath();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri uri ;
if (Build.VERSION.SDK_INT >= 24) {
//这里的权限是 {applicationid}.provider
uri = FileProvider.getUriForFile(context.getApplicationContext(), "com.gomoov.customer.provider", photoFile);
} else {
uri = Uri.fromFile(photoFile);
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
context.startActivityForResult(takePictureIntent,
request);
}
}
return filePath;
}