[英]Can't open pdf file for intent android
我已徹底檢查pdf文件位於/storage/emulated/0/Download/Abcd.pdf"
但無法故意打開它。
我在各種查看器中打開了它,有的哦,這會導致錯誤:“無法打開文件”。 Microsoft word說: check file in the device
,但是當我在android的文件系統中的文件目錄中打開Abcd.pdf
文件時,它打開的很好。
我把路線設置錯了嗎?
AndroidManifest.xml中
<provider
android:authorities="${applicationId}.provider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
MainActivity.Java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent();
File mypath=new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/","Abcd.pdf");
Log.e("download",mypath.getAbsolutePath());
//this log says : /storage/emulated/0/Download/Abcd.pdf
Uri pdfUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", mypath);
Log.e("download",mypath.exists()+"");
if (mypath.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("download","result : "+pdfUri.getPath());
intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/pdf");
intent.putExtra(MediaStore.EXTRA_OUTPUT, pdfUri);
}else{
}
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Log.e("error","error"+e);
}
}
}
RES / XML / provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="storage/emulated/0"
path="."/>
</paths>
我正在使用此功能:
public void openPdf(LocalFile magazine) {
if (BuildConfig.DEBUG)
Log.d(TAG, "openPdf() called with: magazine = [" + magazine + "]");
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
File file = new File(Uri.parse(magazine.getPath()).getPath());
Uri uri = FileProvider.getUriForFile(getContext(),
getContext().getApplicationContext().getPackageName() + ".provider", file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
intent.setDataAndType(Uri.parse(magazine.getPath()), "application/pdf");
}
try {
startActivity(intent);
} catch (Throwable t) {
t.printStackTrace();
//attemptInstallViewer();
}
}
這對我來說很好。
我有一個問題可以解決,您是否在清單中寫了存儲權限?
另外,您的應用還具有讀取外部存儲的權限嗎? 從“移動設置”中進行檢查,它將自動開始工作。
這是在清單文件中初始化Permissions語句的方法。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
如果在清單中給出了該密碼,並且您的移動設備已確保權限並且應用程序無法正常工作,請共享完整的活動代碼,我可能會幫助您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.