博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

023、在手机上实现打开文件功能

Posted on 2013-09-27 21:54  mz_zyh  阅读(392)  评论(0编辑  收藏  举报
手机上打开文件代码:
    /**
     * 在手机上打开文件的方法
     * 
     * @param file
     */
    private void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        // 调用getMIMEType方法获取文件的MimeType
        String type = getMiMEType(file);
        // 设置intent的file与MimeType
        intent.setDataAndType(Uri.fromFile(file), type);
        startActivity(intent);
    }
 
    /**
     * 获取文件的MimeType
     * 
     * @param file
     * @return
     */
    private String getMiMEType(File file) {
        String type;
        String fileName = file.getName();
        // 取得扩展名
        String end = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 根据扩展名的类型决定MimeType
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            type = "image";
        } else {
            // 如果无法直接打开,就跳出软件列表供用户选择
            type = "*";
        }
        type += "/*";
 
        return type;
    }

 

 
其中使用intent.setDataAndType(Uri,type) 指定要打开的文件及文件的MIME Type,并以startActivity()的方式打开文件。在getMIMEType()方法中,依据文件的扩展名来设置该文件的MIME Type,MIIME Type 格式为“文件类型/文件扩展名”,目前程序中仅针对部分类型的文件做MIME Type的判断,其余的文件则一律将MIME Type设置为“*/*”,当系统接收到文件的类型为“*”时,会自动弹出应用程序的菜单,让用户选择要用哪个程序来打开文件。