Sobes.tech
Junior

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.

  1. Using FileProvider (Recommended method for Android N and above):
    The safest and recommended way, as it prevents FileUriExposedException on newer Android versions.

    • You need to define FileProvider in AndroidManifest.xml and create an XML file with file paths.

    • Obtain Uri using FileProvider.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);
      }
      
  2. 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 Intent causes FileUriExposedException when 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.