1、在res目录下新建一个xml目录,里面新建一个名为file_paths的xml文件,文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources >
<paths>
<external-path path="" name="download"/>
<external-path name="external_files" path="."/>
<!--1、对应内部内存卡根目录:Context.getFileDir()-->
<files-path
name="int_root"
path="/" />
<!--2、对应应用默认缓存根目录:Context.getCacheDir()-->
<cache-path
name="app_cache"
path="/" />
<!--3、对应外部内存卡根目录:Environment.getExternalStorageDirectory()-->
<external-path
name="ext_root"
path="pictures/" />
<!--4、对应外部内存卡根目录下的APP公共目录:Context.getExternalFileDir(String)-->
<external-files-path
name="ext_pub"
path="/" />
<!--5、对应外部内存卡根目录下的APP缓存目录:Context.getExternalCacheDir()-->
<external-cache-path
name="ext_cache"
path="/" />
</paths>
</resources>
2、在androidMainfast里添加
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.viewpaerdemo.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
android:authorities="com.example.viewpaerdemo.provider"这里是包名.provider。
3.添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
4、activity里的打开代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 加入此代码,解决FileUriExposedException问题
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
// builder.detectAll();删除检测APK中调试代码是否暴露敏感信息
}
}
public void openPdf() {
String path1 = Environment.getExternalStorageDirectory().getPath();
File file = new File(path1 + "/", "**.pdf");
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri;
if(Build.VERSION.PREVIEW_SDK_INT>=Build.VERSION_CODES.N){
//通过fileProvider创建一个content类型的uri
uri=FileProvider.getUriForFile(this,"com.example.viewpaerdemo.provider",file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else {
uri=Uri.fromFile(file);
}
intent.setDataAndType(uri,"application/pdf");
if(file.exists()) {
this.startActivity(intent);
}
}
他会使用你手机中存在的阅读器打开,完结。