zoukankan      html  css  js  c++  java
  • 023、在手机上实现打开文件功能

    手机上打开文件代码:
        /**
         * 在手机上打开文件的方法
         * 
         * @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设置为“*/*”,当系统接收到文件的类型为“*”时,会自动弹出应用程序的菜单,让用户选择要用哪个程序来打开文件。
  • 相关阅读:
    【HDOJ】2774 Shuffle
    【POJ】2170 Lattice Animals
    【POJ】1084 Square Destroyer
    【POJ】3523 The Morning after Halloween
    【POJ】3134 Power Calculus
    【Latex】如何在Latex中插入伪代码 —— clrscode3e
    【HDOJ】4801 Pocket Cube 的几种解法和优化
    【HDOJ】4080 Stammering Aliens
    【HDOJ】1800 Flying to the Mars
    SQL语法
  • 原文地址:https://www.cnblogs.com/zyh-blog/p/3343659.html
Copyright © 2011-2022 走看看