我试图在我的Android应用程序上显示不同类型的文件,但它只适用于PDF文件,当我尝试显示任何其他类型的文件时。我收到一个错误说:
无法显示pdf,文件格式无效
以下是我的代码片段:
else if (currentFile.toString().contains(".pdf")) {
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(".PDF");
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(currentFile), mime);
startActivityForResult(intent, 10);
} else if (currentFile.toString().contains(".doc")||currentFile.toString().contains(".docx")) {
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(".doc");
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(currentFile), mime);
startActivityForResult(intent, 10);
} else if (currentFile.toString().contains(".jpg") || currentFile.toString().contains(".jpeg") || currentFile.toString().contains(".png")){
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(".jpg");
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(currentFile), mime);
startActivityForResult(intent, 10);
}
答案 0 :(得分:0)
我可以自己找到解决方案,这里是我使用过的代码片段
private void openFile(File currentFile, String fileFormat) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(currentFile),fileFormat);
startActivity(intent);
}
我将此方法称为:
...........
} else if (currentFile.toString().contains(".pdf"))
openFile(currentFile,"application/pdf");
else if (currentFile.toString().contains(".doc") || currentFile.toString().contains(".docx"))
openFile(currentFile,"application/msword");
else if (currentFile.toString().contains(".jpg") ||
currentFile.toString().contains(".jpeg") || currentFile.toString().contains(".png"))
openFile(currentFile,"image/jpeg");
else if(currentFile.toString().contains(".ppt") || currentFile.toString().contains(".pptx"))
// Powerpoint file
openFile(currentFile,"application/vnd.ms-powerpoint");
else if(currentFile.toString().contains(".xls") || currentFile.toString().contains(".xlsx"))
// Excel file
openFile(currentFile, "application/vnd.ms-excel");
else if(currentFile.toString().contains(".zip") || currentFile.toString().contains(".rar"))
// WAV audio file
openFile(currentFile,"application/x-wav");
else if(currentFile.toString().contains(".rtf"))
// RTF file
openFile(currentFile,"application/rtf");
else if(currentFile.toString().contains(".wav") || currentFile.toString().contains(".mp3"))
// WAV audio file
openFile(currentFile,"audio/x-wav");
else if(currentFile.toString().contains(".gif"))
// GIF file
openFile(currentFile,"image/gif");
else if(currentFile.toString().contains(".txt"))
// Text file
openFile(currentFile,"text/plain");