我面對這個錯誤:試圖打開pdf文件的Android
E/AndroidRuntime: java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.mobgen.androidinterviewtest/files/LaFerrari.pdf
E/AndroidRuntime: at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:678)
E/AndroidRuntime: at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:377)
E/AndroidRuntime: at com.mobgen.interview.SingleCarActivity$1.onClick(SingleCarActivity.java:92)
這是因爲該行的代碼:
Uri uri = FileProvider.getUriForFile(SingleCarActivity.this, "be.myapplication", file);
我跟了,我已經找到了資源: http://developer.android.com/reference/android/support/v4/content/FileProvider.html
Open file in cache directory with ACTION_VIEW
How to use support FileProvider for sharing content to other apps?
但是我仍然無法解決我遇到的錯誤。
下面你可以看到我的代碼:
SingleCarActivity.java:
File file = new File(getFilesDir(), pdf); //pdf contains "LaFerrari.pdf"
Uri uri = FileProvider.getUriForFile(SingleCarActivity.this, "be.myapplication", file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
的AndroidManifest.xml:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="be.myapplication"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_pdf" path="assets/"/>
</paths>
下面你可以看到我的項目結構如何的屏幕截圖: 鏈接:http://i.imgur.com/4dbhcKF.png
'assets /'是開發機器上的一個目錄。它不是設備上的目錄。 'FileProvider'不能提供資產,只能提供本地文件。你是否將這些文件從資產複製到'getFilesDir()'下的'assets /'子目錄? – CommonsWare
@CommonsWare我用Google搜索了它。你的意思是類似於以下問題的答案嗎?鏈接:http://stackoverflow.com/questions/8474821/how-to-get-the-android-path-string-to-a-file-on-assets-folder – superkytoz