您的位置:首页 > 移动开发 > Android开发

Android调用适当程序打开文件的万能方法

2016-01-12 17:57 555 查看


假如你的app想打开一个储存在手机上的一个文件如apk打开安装、图片打开观看、pdf用AdobeAcrobat打开等等,而你不可能为每种文件都写个打开方法,为此给大家抛出一个简单的方法。

/**
* TODO 打开某文件
*
* @param context     context
* @param destination 文件目录
*/
public static void openFile(Context context, String destination) throws Exception {
if (!new File(destination).exists()) {
//文件不存在
return;
}
//文件路径
if (!destination.contains("file://")) {
destination = "file://" + destinatio
9b54
n;
}
//获取文件类型
String[] nameType = destination.split("\\.");
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(nameType[1]);
//intent
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
//设置文件的路径和文件类型
intent.setDataAndType(Uri.parse(destination), mimeType);
//跳转
context.startActivity(intent);
}

思路就是分析文件路径得到后缀名,然后通过后缀名分析MimeType,最后生成Intent即可。

例如手机里有个pdf,叫"xxx/yy/zz.pdf",最后会分析出MimeType为"application/pdf",最后会调出如图所示的界面。

这里用到了Android自带的MimeTypeMap,只要是这里有的后缀名,都能分析出MimeType。

这个方法有可能会报错,因为你有可能没装打开某类型文件的App。Try Catch即可。

即兴随写,欢迎抛砖
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: