Skip to content

Setup of FileProvider

Jiří M. aka Menion edited this page Feb 21, 2019 · 2 revisions

FileProvider

Since Android 5.0+, shading of content by directly sending absolute path to files is no longer possible. For sharing is now necessary to use a special version of contentProvider, so-called FileProvider.

Basic setup

Steps below are used in sample API application, so feel free to use it as well for it's simplicity.

  1. Setup authority In XML with your strings, it may be strings.xmlor rather separately something like config.xml, set
<string name="file_provider_authority" translatable="false">com.asamm.locus.api.sample.provider</string>
  1. Setup paths It is necessary to setup paths, that we will use for sharing files. In res/xml create file filepaths.xml with content below. Use only paths useful for you. More in official Google documentation.
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path
        name="files_path"
        path="/" />
    <cache-path
        name="cache_path"
        path="/" />
    <!-- File(ctx.cacheDir, "shared") -->
    <cache-path
        name="cache_path_shared"
        path="/shared" />
    <external-path
        name="external_files"
        path="/" />
    <external-files-path
        name="external_files_path"
        path="/" />
    <external-cache-path
        name="external_cache_path"
        path="/" />
</paths>
  1. Setup manifest In AndroidManifest.xml set provider as
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="@string/file_provider_authority"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepaths" />
</provider>
  1. Use API functions (that require Uri to file) or share files on your own with
// generate Uri over FileProvider
val uri = FileProvider.getUriForFile(ctx, ctx.getString(R.string.file_provider_authority), file)

// send request for "display"
val send = ActionFiles.importFileLocus(ctx, uri, ActionFiles.getMimeType(file), lv, false)

Few tips

  • in case, you share files out of app private directories, do not forget that android.permission.READ_EXTERNAL_STORAGE permission need your app, not app that catch intent.
Clone this wiki locally