2

My goal is to open pdf file from any memory.

I use android emulator with device memory and also removable SD-Card.

So pathes look like:

/storage/emulated/0/hts221.pdf - device memory

/storage/1317-231C/LPS22HB.pdf - removable SD-Card

Using this code to open file (where fileName is one of the two above):

 File file = new File(fileName);
 Intent target = new Intent(Intent.ACTION_VIEW);
 Uri fileURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
 target.setDataAndType(fileURI,"application/pdf");
 target.setFlags(target.getFlags() | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION );
 Intent intent = Intent.createChooser(target, "Open File");
 context.startActivity(intent);

AndroidManifest.xml

<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/provier_path

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

Problem:

When I try to open pdf file from device memory (/storage/emulated/0/hts221.pdf) - Everything works fine.

But, when I try to open pdf file from SD-Card (/storage/1317-231C/LPS22HB.pdf) - Application crashes with:

W System.err: java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/1317-231C/LPS22HB.pdf
W System.err:   at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
W System.err:   at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)

What am I missing here? I guess the problem is somewhere in xml/provier_path.

I use Qt Android, but I think this is not really matter in this case.

Shunt
  • 179
  • 8

2 Answers2

2

Added

 <root-path name="root" path="." />

to xml/provider_path. And both files work fine now.

Shunt
  • 179
  • 8
1

FileProvider cannot serve files from a removable micro sd card.

If you want to serve files from a removable micro sd card then extend ContentProvider to do so.

It is hard to believe that root-path will solve the issue but i will check soon.

Update: Indeed that works. On android 11 the Android/data stays closed though.

Great find! (I think i saw it before but forgot. Well ... all questions and answers are duplicates here you know.).

blackapps
  • 8,011
  • 2
  • 11
  • 25
  • See: https://stackoverflow.com/questions/40318116/fileprovider-and-secondary-external-storage – blackapps Nov 03 '20 at 09:16
  • Thank you. Someone issued a bug report in your link (https://stackoverflow.com/a/40702794/2758504) and it's wont fix. Frustrating – Shunt Nov 03 '20 at 10:29