2

For Android 8 and 9 only.

I have a PDF filer here -

String url = "file:///storage/emulated/0/Android/data/com.verna.poc/files/Download/mypdf.pdf";

I'm trying to open this file for viewing using this -

File file= new File(url);
file.setReadable(true, false);

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri pdfUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
intent.setDataAndType(pdfUri, "application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

List<ResolveInfo> resInfoList = getApplicationContext().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        getApplicationContext().grantUriPermission(packageName, pdfUri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

Intent in = Intent.createChooser(intent, "Open File");
startActivity(in);

The File chooser option is opening and when I open the file using Google PDF reader, the PDF reader opens and closes immediately. Whats wrong in my code ?

4
  • have you provided read write permission?
    – karan
    Mar 2, 2019 at 4:35
  • yes i have. my manifest has these - <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET"/> Mar 2, 2019 at 4:37
  • they need runtime confirmation from user, did you do that?
    – karan
    Mar 2, 2019 at 4:39
  • yes. i have given runtime persmissions for these as well. still not working. Mar 2, 2019 at 5:04

4 Answers 4

1

access the file from within the app which owns that private directory - an Intent won't cut it, because this could have been sent by just any application. and if it has to be a file-chooser Intent, then create a shared directory for your app on the SD card, where any application can access it; the regular Downloads directory would also be suitable for that. another option (as initially suggested) would be to create a simple file-chooser, which resides within the application, so that no Intent would be required to select a file... this all has certain advances and dis-advances; choose the one possibility, which suits you the best... in general, it's private vs. shared storage location.

3
  • but im using file provider for sharing an internal file to be accessed by a third party app. File providers are used for that purpose, i guess. it would be great if you can give a working solution. Mar 2, 2019 at 4:30
  • @Gissipi_453 you are creating an Intent, which is supposed to be fulfilled by another application, while such one is being installed ... see the documentation: developer.android.com/reference/android/content/… ... that's why messing around with uri-permissions is required - which otherwise would not be required. you could also set it in Manifest.xml already: developer.android.com/guide/topics/manifest/… ...matching all PDF in there. Mar 2, 2019 at 11:18
  • ... while you already grant access, better just use external storage - because then it will be an SD card, (while one is present). with a few files your approach is just fine, with a few hundred or thousands of files, this can get problematic. it doesn't scale nicely - because clearing the data (just try with settings > applications) will delete them altogether, which is not the case with external storage. Mar 2, 2019 at 11:30
1

You are trying to share a file from internal storage with the another app. You will need to create a file provider for this to work. You will need to specify a directory which you want the file provider to generate Uris for

FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri.

A FileProvider can only generate a content URI for files in directories that you specify beforehand. To specify a directory, specify the its storage area and path in XML, using child elements of the element. For example, the following paths element tells FileProvider that you intend to request content URIs for the images/ subdirectory of your private file area.

This answer has a good example on this

link

Here is the doc page for FileProvider

FileProvider

2
  • thanks for the answer. im already using a file provider as you can see in my question. as i figured out later, the issue was with how i was using my file path. When you are making a new file using, File file = new File(path), don't add file:// infront of the path. Mar 2, 2019 at 7:33
  • @Gissipi_453 it would expect protocol scheme content://, which can be omitted (most likely because there only is 1 protocol scheme to "choose" from - and so it is known which one to use, unless telling it otherwise). Mar 2, 2019 at 11:41
1

In this we first save the file to internal storage and then read from it using external app.

I use below method to save the file in internal storage :

private void savePDFtoInternalStorage(byte[] pdfAsBytes){
    //Save in internal memo cache
    File directory = mFragmentActivity.getFilesDir();
    //updating path for pdf to match with file_path.xml
    mCardStmtFile = new File(directory.getAbsolutePath(), "sample.pdf");
    OutputStream outputStream = null;
    try {
        PbLogger.e(TAG, "writing to mStmtFile");
        outputStream = new FileOutputStream(mCardStmtFile, false);
        outputStream.write(pdfAsBytes);
        outputStream.flush();
        outputStream.close();

    } catch (IOException e) {
        e.printStackTrace();

    }
}

PFB the file provider declared file_path.xml:

  <?xml version="1.0" encoding="utf-8"?>
   <paths>
      <files-path path="/" name="secretpdf" />
   </paths>

PFB the Android Manifest Entry for file provider :

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.***.********.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <!-- ressource file to create -->
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths">
        </meta-data>
    </provider>

Use below code to launch PDF :

 Intent intentShareFile = new Intent(Intent.ACTION_VIEW);
        if (mStmtFile.exists()) {
            intentShareFile.setType("application/pdf");
            Uri fileUri = FileProvider.getUriForFile(
                    mFragmentActivity,
                    "com.****.********.provider",
                    mCardStmtFile);
            intentShareFile.putExtra(Intent.EXTRA_STREAM, fileUri);
            intentShareFile.putExtra(Intent.EXTRA_SUBJECT,
                    getDescription());
            //adding grant read permission to share internal file
            intentShareFile.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(intentShareFile, "Share File"));
        }
0

I got the issue. When you are making a new file using, File file = new File(path), don't add file:// infront of the path.

This is correct -

String url = "/storage/emulated/0/Android/data/com.verna.poc/files/Download/mypdf.pdf";
File file= new File(url);

This is wrong -

String url = "file:///storage/emulated/0/Android/data/com.verna.poc/files/Download/mypdf.pdf";
File file= new File(url);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.