tezvyn:

FileProvider: Securely Share Files Between Apps

AI-drafted, machine-checkedSource: developer.android.comadvanced

FileProvider is Android's bouncer for files, replacing insecure `file:///` URIs with temporary, permission-granted `content://` URIs. Use it to send a photo for editing or attach a PDF to an email.

WHY IT EXISTS: Before Android 7.0 (Nougat), apps could share files using file:/// URIs, which exposed direct file system paths. This was a security risk, allowing malicious apps to discover and potentially access private data. To fix this, Android blocked file:/// URIs from being passed between apps, which throws a FileUriExposedException.

THE MENTAL MODEL: Think of a FileProvider as a valet key for a file. Instead of giving another app the keys to your entire private directory (the raw file path), you give it a temporary, restricted key (content:// URI) that only works for one specific file. The other app can use the file, but it can't see where it's stored or access anything else.

HOW IT WORKS: You first declare the FileProvider in your AndroidManifest.xml, specifying a unique authorities string. Second, you create an XML resource file (e.g., res/xml/file_paths.xml) to explicitly define which directories your app is allowed to share files from. Finally, in your code, you call FileProvider.getUriForFile() to generate the secure content:// URI. When you add this URI to an Intent, you must also grant temporary access by adding flags like Intent.FLAG_GRANT_READ_URI_PERMISSION.

WHEN TO USE IT: Use FileProvider any time you need to send a file from your app's private storage (internal or external cache/files directories) to another app. This includes attaching a generated document to an email client, sending an image to a cropping app, or prompting the system to install an APK update you've downloaded.

WHEN NOT TO USE IT: It's not necessary for files already in public shared storage (like the Downloads or Pictures folders), where the MediaStore API is more appropriate. FileProvider is specifically for sharing files from your app's sandboxed directories. It is also not needed for passing file data within your own app; just pass the File object directly.

ONE CANONICAL EXAMPLE: To let the user take a picture that your app can use, you first define a path for the image file in your app's cache. You then generate a content:// URI for that path using FileProvider.getUriForFile(). You pass this URI as an extra (MediaStore.EXTRA_OUTPUT) in an ACTION_IMAGE_CAPTURE Intent, granting write permission. The camera app takes the photo, writes it to your URI, and your app receives the result without ever exposing its private file structure.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.