How to pass a file link in an Intent?
sobes.tech AI
Answer from AI
To pass a file link in an Intent, Uri is used.
-
Using
FileProvider(Recommended method for Android N and above):
The safest and recommended way, as it preventsFileUriExposedExceptionon newer Android versions.-
You need to define
FileProviderinAndroidManifest.xmland create an XML file with file paths. -
Obtain
UriusingFileProvider.getUriForFile(). -
AndroidManifest.xml:<application> <provider android:name="androidx.core.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> </application> -
res/xml/provider_paths.xml:<paths> <external-path name="external_files" path="."/> </paths> -
Transfer code:
// Assuming 'file' is a java.io.File object Uri fileUri = FileProvider.getUriForFile( context, context.getPackageName() + ".provider", file ); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(fileUri, "application/pdf"); // Specify the correct MIME type intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Grant read permission if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(intent); }
-
-
Using
Uri.fromFile()(Deprecated from Android N):
This method is not recommended on newer Android versions due to security issues.-
Starting from Android N, passing file URIs via
IntentcausesFileUriExposedExceptionwhen interacting with apps outside the current app. -
Transfer code:
// Assuming 'file' is a java.io.File object Uri fileUri = Uri.fromFile(file); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(fileUri, "application/pdf"); // Specify the correct MIME type // This code may cause FileUriExposedException on Android N+ when interacting with other apps if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(intent); }
-
Brief table:
| Method | Recommendation (Android N+) | Security |
|---|---|---|
FileProvider |
✅ | High (prevents FileUriExposedException) |
Uri.fromFile() |
❌ | Low (may cause FileUriExposedException) |
Always use FileProvider for sharing files between apps on Android N and above.