FileProvider实际上是ContentProvider的一个子类,android7.0以前文件路径是file://Uri 7.0开始为content://
第一步:清单文件下声明provider
authorities:代表一个共享的属性设置,自己定义,一般为包名+fileprovider
${applicationId}表示当前gradle下配置的applicationId
resource:表示自定义开放共享路径的文件资源定位
<!--应用间共享数据-->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
//***补充说明,当使用androidx库时 需要作出修改如下
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
第二步:在res下建立xml文件夹并创建paths类型的文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Context.getFilesDir() + "/path/" -->
<files-path
name="my_files"
path="path"/>
<!-- Context.getCacheDir() + "/path/" -->
<cache-path
name="my_cache"
path="path"/>
<!-- Context.getExternalFilesDir(null) + "/path/" -->
<external-files-path
name="external-files-path"
path="path"/>
<!-- Context.getExternalCacheDir() + "/path/" -->
<external-cache-path
name="name"
path="path" />
<!-- Environment.getExternalStorageDirectory() + "/path/" -->
<external-path
name="my_external_path"
path="path"/>
<!-- Environment.getExternalStorageDirectory() + "/path/" -->
<external-path
name="files_root"
path="path"/>
<!-- path设置为'.'时代表整个存储卡 Environment.getExternalStorageDirectory() + "/path/" -->
<external-path
name="external_storage_root"
path="."/>
</paths>
</resources>
第三步:使用FileProvider
//配置好FileProvider后调用拍照示例
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String filename = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA)
.format(new Date()) + ".png";
File file = new File(Environment.getExternalStorageDirectory(), filename);
//生成指定路径的访问URI
Uri fileUri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//这里的参数为privoder中配置的自定义的authorities属性值
fileUri = FileProvider.getUriForFile(this, "com.fox.industry.fileprovider", file);
} else {
fileUri = Uri.fromFile(file);
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, 111);
}
关于7.0开始安装下载的apk进行适配
private void installApp(Context context, String apkPath) {
File apkFile = new File(apkPath);
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri apkUri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
apkUri = FileProvider.getUriForFile(context, "清单文件中配置的authority", apkFile);
} else {
apkUri = Uri.fromFile(apkFile);
}
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
startActivity(intent);
}