androidfileandroid-intenturidocumentfile

Using Intent.ACTION_VIEW together with DocumentFile class


I use this code to achieve "Open in" function for File Class (java.io.File):

...
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getMimeTypeFromExtension(fileExtension);

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), type); // Standard File class            
startActivity(Intent.createChooser(intent, "blabla"));
...

I would like to do the same with DocumentFile class (android.support.v4.provider.DocumentFile):

...
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getMimeTypeFromExtension(fileExtension);

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(documentFile.getUri(), type); // DocumentFile class          
startActivity(Intent.createChooser(intent, "blabla"));
...

However, It seems no application (even on Android 5) is able to handle URI - documentFile.getUri().

Do I do anything wrong?


Solution

  • This worked for me:

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(docFile.getUri(), type);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);