1、在res目錄下新建一個(gè)xml目錄滨嘱,里面新建一個(gè)名為file_paths的xml文件峰鄙,文件內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources >
<paths>
<external-path path="" name="download"/>
<external-path name="external_files" path="."/>
<!--1、對(duì)應(yīng)內(nèi)部?jī)?nèi)存卡根目錄:Context.getFileDir()-->
<files-path
name="int_root"
path="/" />
<!--2太雨、對(duì)應(yīng)應(yīng)用默認(rèn)緩存根目錄:Context.getCacheDir()-->
<cache-path
name="app_cache"
path="/" />
<!--3吟榴、對(duì)應(yīng)外部?jī)?nèi)存卡根目錄:Environment.getExternalStorageDirectory()-->
<external-path
name="ext_root"
path="pictures/" />
<!--4、對(duì)應(yīng)外部?jī)?nèi)存卡根目錄下的APP公共目錄:Context.getExternalFileDir(String)-->
<external-files-path
name="ext_pub"
path="/" />
<!--5囊扳、對(duì)應(yīng)外部?jī)?nèi)存卡根目錄下的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.添加權(quán)限
<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();刪除檢測(cè)APK中調(diào)試代碼是否暴露敏感信息
}
}
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創(chuàng)建一個(gè)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);
}
}
他會(huì)使用你手機(jī)中存在的閱讀器打開,完結(jié)搏予。