我正在尝试使用 Intents 打开任何任意文件。但是,对于已安装可以打开它们的应用程序的文件类型,我收到 ActivityNotFoundException。在下面的源代码中,当 file
指向 PNG 文件时,我会看到“使用完成操作”对话框。但是,当我尝试打开 mp3 时,出现异常。当我打开 Astro 并单击同一个 mp3 文件时,我会看到“使用完整操作”对话框,其中显示已安装的 MP3 播放器。如何从我的代码中显示相同的对话框?当我从调试器检查文件位置、扩展名和 MIME 类型时,它们看起来都是正确的。
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);
答案是 Intent.setType
和 Intent.setData
是互斥的。调用一个可以清除另一个。因此,调用 setDataAndType
即可解决问题。
最佳答案
试试这个:
Intent newIntent = new Intent();
newIntent.setDataAndType(Uri.parse("file://"+filePath),mimeType);
newIntent.setAction(Intent.ACTION_VIEW);
try {
startActivity(newIntent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No handler for this type of file.", 4000).show();
}
关于android - 打开任意文件类型的正确 Intent 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13923391/