I am trying to open any arbitrary file using Intents. However, I get the ActivityNotFoundException for file types for which there are installed apps that can open them. In the source below, when file points to a PNG file, I get the “Complete action using” dialog. However, when I try to open an mp3, I get the exception. When I open Astro and click on the same mp3 file, I get the “Complete action using” dialog showing the installed MP3 players. How do I get the same dialog to show up from my code? The file location, extension, and MIME type all look correct when I inspect them from the debugger.
String url = file.toURL().toString();
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
String type = typeMap.getMimeTypeFromExtension(extension);
mimeType.setText(type);
boolean fileExists = file.exists();
Intent viewIntent = new Intent(Intent.ACTION_VIEW);
viewIntent.setData(Uri.fromFile(file));
viewIntent.setType(type);
MainActivity.this.startActivity(viewIntent);
The answer is that Intent.setType and Intent.setData are mutually exclusive. Calling one clears out the other. So calling setDataAndType is the fix.
Try this: