Content providers

Lifecycle and app components Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

Sharing a PDF with Uri.fromFile(file) crashes. What's the fix?

Options
Hint 1 of 1

Which URI scheme can be shared across apps?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Get a content:// URI from FileProvider and grant read permission

Correct. file:// URIs can't be shared across apps since Android 7.

Why not the others?
  • B Request MANAGE_EXTERNAL_STORAGE. That's a broad permission Play restricts, and doesn't fix the URI type.
  • C Copy the PDF to a public folder first. Still a file:// URI, and leaks the file.
  • D Use an implicit intent with ACTION_VIEW. The URI type is the problem, not the action.

30-second answer

A ContentProvider exposes structured data to other apps through content:// URIs with query, insert, update and delete, and enforces permissions on it. You need one to share data with other apps, for search suggestions, or to serve files through FileProvider. For data used only inside your app, a Room database or repository is simpler.

Practise saying it · 30 s. No recording, just a timer

Explain when you need a ContentProvider.

Say your answer out loud, then check which of these points you covered:

  • Share data with other apps
  • FileProvider for files
  • Not for internal data
  • Grant temporary URI permissions

Deep dive

FileProvider is the standard way to share a file, such as a photo for the camera to write, with a temporary URI permission.

Reading contacts, media and calendar goes through system providers with ContentResolver.

Providers are created before Application.onCreate, which is why some libraries used them for initialisation; App Startup replaces that pattern.

Grant temporary access with FLAG_GRANT_READ_URI_PERMISSION rather than exporting the provider.

Common mistakes

  • Building a ContentProvider for data only your app reads.
  • Sharing file:// URIs, which throws FileUriExposedException.
  • Exporting a provider with no permissions.

Senior take & follow-ups

Know when you need one and name FileProvider; that's the most common real use.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you let the camera app save a photo for you?

    Show hint

    Create a FileProvider URI and grant write permission in the intent.

  2. Why did libraries use providers for init?

    Show hint

    They run automatically before Application.onCreate.

Suggest a fix if something here is wrong or out of date.