2

I've looked at several examples like File provider throws exception but I can't seem to get my file provider to work for everyone. I've tested it myself on Android 8 and it works fine, but for some users it throws IllegalArgumentException.

It looks like:

Manifest
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="com.my.app.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths" />
</provider>

Paths file

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-cache-path name="cache_dir" path="/" />
</paths>

Sharing:

File path = context.getExternalCacheDir().getAbsolutePath();
path += filename;
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Shared file");
sendIntent.putExtra(Intent.EXTRA_STREAM, getUriForFile(context, "com.my.app.fileprovider", path));
sendIntent.setType("application/octet-stream");
context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.strBackup)));

The exception:

java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/3764-3933/Android/data/com.my.app/cache/backup.bin
    at androidx.core.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:739)
...

What should the file provider paths file looks like to work for all users? And why does it work for most Android 8+ users, but not all? Should I use a path like . or ./ instead?

Mackan
  • 1,305
  • 2
  • 17
  • 30
  • Are you sure that you are consistently getting `path` from `context.getExternalCacheDir()`? The path shown in your error message looks like it is from removable storage, not external storage. If you do not need this file to be on external storage, consider internal storage (`getCacheDir()`), and that should be less likely for device manufacturers to tamper with. – CommonsWare Jan 31 '19 at 00:21
  • Thanks, I'll try to change to getCacheDir instead. But is the filepath correct, to use `/`, or should I use some other file path? – Mackan Jan 31 '19 at 08:57
  • Usually we don't share *all* of a location like `getCacheDir()` or `getExternalCacheDir()`. Usually, we create a subdirectory in there, and share that. If you go that route, the subdirectory goes in `path` (e.g., `path="public/"`). – CommonsWare Jan 31 '19 at 11:49
  • Did you resolve the issue? My app was working just fine when I used appcompat, but it started throwing this exception after I migrated to Androidx. – KMC Jul 10 '20 at 02:22
  • I set the file paths like this and it worked ` ` – Mackan Jul 10 '20 at 16:44

0 Answers0