1,AndroidManifest注册provider
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="你的包名"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
2,xml文件申请根目录权限
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<root-path
name="root"
path="" />
<external-files-path
name="name"
path="path" />
<external-cache-path
name="name"
path="path" />
</paths>
3,调用封装intent
Intent intent = new Intent();
try {
Path paths = Paths.get(file.toURI());
Uri uri=null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
String uriPath = Uri.encode(paths.toUri().toString());
uri = new Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(BuildConfig.APPLICATION_ID)
.path(uriPath)
.build();
} else {
// PackageInstaller only supports file URI before N.
uri = Uri.fromFile(paths.toFile());
}
int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
flags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION
| Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
if (mFileItem.isfIsDir()) {
flags |= Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
}
intent.addFlags(flags);
intent.setData(uri);
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
|