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设置为“*/*”,当系统接收到文件的类型为“*”时,会自动弹出应用程序的菜单,让用户选择要用哪个程序来打开文件。
  • 相关阅读:
    实时信号阻塞队列大小测试
    实时信号和非实时信号
    [Linux]关于sigprocmask函数的讨论
    java中Map集合的常用方法 (转)
    佛跳墙
    百万数据查询效率提高方法(转)
    bootstrap table 前后端分页(超级简单)
    bootstrap table 分页序号递增问题 (转)
    Spring boot+mybatis+thymeleaf 实现登录注册,增删改查
    js弹出对话框的三种方式(转)
  • 原文地址:https://www.cnblogs.com/zyh-blog/p/3343659.html
Copyright © 2011-2022 走看看