1. 创建FileProvider放在项目xml里面
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fec19cac51b46b14ad2a0ff130fa98b1.png)
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<root-path
name="root-path"
path="" />
<external-path
name="download"
path="/glacier/house/download/" />
</paths>
2. 在AndroidManifest添加provider
- 马赛克部分填写你的包名
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/246d4a3486380e2248ea526705ba5a4c.png)
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${填写包名}.fileprovider"
android:exported="false"
tools:replace="android:authorities"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
tools:replace="android:resource"
android:resource="@xml/filepaths"
/>
</provider>
3. 打开文件
public static void openAndroidFile(String filepath, Context context) {
Intent handlerIntent = new Intent();
File file = new File(filepath);
handlerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
handlerIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
String type = getMIMEType(file);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
handlerIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
handlerIntent.setDataAndType(uri, type);
context.startActivity(handlerIntent);
} else {
handlerIntent.setDataAndType(uri, type);
context.startActivity(handlerIntent);
}
}
private static void openFile(Context context, File f) {
Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString());
String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
myIntent.setDataAndType(Uri.fromFile(f),mimetype);
context.startActivity(myIntent);
}