我正在尝试使用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
就是问题所在。
答案 0 :(得分:2)
试试这个:
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();
}