public static void openFile(File file, Context context) {
//需要捕获异常,比如说你的MIME类型是打开邮箱,但是你手机里面没装邮箱客户端,就会报错。
try {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
//获取文件file的MIME类型
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(file.getPath()));
//设置intent的data和Type属性。
intent.setDataAndType(/*uri*/Uri.fromFile(file), mimeType);
//跳转
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.i(TAG, "没有支持的应用"); }
}
上面的方法如果文件名称中包含中文得到的额mimeType会为空改进后的版本
/**
* 打开文件
*
* @param file
*/
public static void openFile(File file, Context context) {
try {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
//获取文件file的MIME类型
String extension = getExtension(file);
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(extension);
//设置intent的data和Type属性。
intent.setDataAndType(/*uri*/Uri.fromFile(file), mimeType);
//跳转
context.startActivity(intent); //这里最好try一下,有可能会报错。 //比如说你的MIME类型是打开邮箱,但是你手机里面没装邮箱客户端,就会报错。
} catch (ActivityNotFoundException e) {
AbToastUtil.showToast(context, R.string.no_support_app);
}
}
// 获取文件后缀
private static String getExtension(final File file) {
String suffix = "";
String name = file.getName();
final int idx = name.lastIndexOf(".");
if (idx > 0) {
suffix = name.substring(idx + 1);
}
return suffix;
}
参考:
http://zengyan2012.iteye.com/blog/1646492