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设置为“*/*”,当系统接收到文件的类型为“*”时,会自动弹出应用程序的菜单,让用户选择要用哪个程序来打开文件。
  • 相关阅读:
    HDU1883 Phone Cell
    HDU2297 Run
    关于反射的疑惑
    struts2+spring 实例教程
    在.Net 模板页中使用CSS样式
    到底是什么反射,泛型,委托,泛型
    asp.net如何实现删除文件夹及文件内容操作
    学好C#方法
    Web网页安全色谱
    总结一些ASP.NET常用代码
  • 原文地址:https://www.cnblogs.com/zyh-blog/p/3343659.html
Copyright © 2011-2022 走看看