UIDocumentInteractionController equivalent for Android Java

Viewed 124

I would like my android application to display a dialog that allows the user to open a file in another application or save the file much like the UIDocumentInteractionController for iOS that displays an "Open in..." dialog for a particular document. Does this not exist in the Android SDK?

UIDocumentInteractionController

1 Answers

After some trial and error, I managed to find a reasonable solution, but not the equivalent to the iOS UIDocumentInteractionController, that uses minimal custom activity code, which just uses an ACTION_VIEW intent.:

private void showDialogForFile(File file, String extension) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setType(MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
    Uri uri = FileProvider.getUriForFile(getBaseContext(), 
      getApplicationContext().getPackageName() + ".provider", file);
    intent.setData(uri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(intent);
}

I also needed to add the following to my Android manifest:

<provider 
  android:authorities="${applicationId}.fileprovider"
  android:exported="false" 
  android:grantUriPermissions="true" 
  android:name="android.support.v4.content.FileProvider">
    <meta-data 
      android:name="android.support.FILE_PROVIDER_PATHS" 
      android:resource="@xml/file_paths" />
</provider>

And then add to the resource file res/xml/file_paths.xml

<?xml version='1.0' encoding='utf-8'?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>
Related