2017-04-02 54 views
1

我對Android編程比較陌生,並遵循幾個不同的教程。 目標是將pdf文件從資產文件夾複製到外部存儲,然後在按下按鈕打開PDF-Viewer時打開一個Intent。我試圖調節我的代碼使用FileProvider最新的Android版本如下所述:https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/enAndroid FileProvider無法找到文件

開幕較舊的Android版本的文件工作,所以我知道,整個複製過程的工作,事情是我實在不明白在我的代碼錯誤的地方。

File file = new File(Environment.getExternalStorageDirectory() + "/" + "index.pdf"); 
    Intent intent = new Intent(Intent.ACTION_VIEW); 
    //old version 
    Uri fileURI = Uri.fromFile(file); 
    //new version 
    Uri fileUri = FileProvider.getUriForFile(MainActivity.this, 
      BuildConfig.APPLICATION_ID + ".provider", file); 

    getApplicationContext().grantUriPermission(PACKAGE_NAME, fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); 
    intent.setDataAndType(fileUri,"application/pdf"); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

我按照上面的鏈接設置了我的FileProvider。

<provider 
     android:name="android.support.v4.content.FileProvider" 
     android:authorities="${applicationId}.provider" 
     android:exported="false" 
     android:grantUriPermissions="true"> 
     <meta-data 
      android:name="android.support.FILE_PROVIDER_PATHS" 
      android:resource="@xml/provider_paths"/> 
    </provider> 

使用下面的XML

<?xml version="1.0" encoding="utf-8"?> 
<paths xmlns:android="http://schemas.android.com/apk/res/android"> 
<external-path name="external_files" path="."/> 
</paths> 

,我會很高興,如果有人可以解釋我我的錯誤。

+0

你什麼錯誤到底是什麼?在你的應用程序?或者在用戶選擇的應用程序?不清楚。 – greenapps

+0

您應該只建立的意圖是'file.exists()'是真實的。添加該代碼。 – greenapps

+0

從評論:我不得不添加intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);也。 – greenapps

回答

2

從評論:我不得不添加intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);也。