Android获取文件的mimeType的封装

概述

MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型。是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。

步骤


  • 1.定义各种文件对应的mimeType的xml文件

在res目录下面创建一个xml文件夹,在此文件夹下面创建对应xml文件

<MimeTypes>
    <type extension=".png" mimetype="image/png" />
    <type extension=".gif" mimetype="image/gif" />
    <type extension=".jpg" mimetype="image/jpeg" />
    <type extension=".jpeg" mimetype="image/jpeg" />
    <type extension=".bmp" mimetype="image/bmp" />
    <type extension=".mp2" mimetype="audio/x-mpeg" />
    <type extension=".mp3" mimetype="audio/mp3" />
    <type extension=".wav" mimetype="audio/wav" />
    <type extension=".ogg" mimetype="audio/x-ogg" />
    <type extension=".mid" mimetype="audio/mid" />
    <type extension=".midi" mimetype="audio/midi" />
    <type extension=".m3u" mimetype="audio/x-mpegurl" />
    <type extension=".m4a" mimetype="audio/mp4a-latm" />
    <type extension=".m4b" mimetype="audio/mp4a-latm" />
    <type extension=".m4p" mimetype="audio/mp4a-latm" />
    <type extension=".mpga" mimetype="audio/mpeg" />
    <type extension=".wma" mimetype="audio/x-ms-wma" />
    <type extension=".mpe" mimetype="video/mpeg" />
    <type extension=".mpg" mimetype="video/mpeg" />
    <type extension=".mpeg" mimetype="video/mpeg" />
    <type extension=".3gp" mimetype="video/3gpp" />
    <type extension=".asf" mimetype="video/x-ms-asf" />
    <type extension=".avi" mimetype="video/x-msvideo" />
    <type extension=".m4u" mimetype="video/vnd.mpegurl" />
    <type extension=".m4v" mimetype="video/x-m4v" />
    <type extension=".mov" mimetype="video/quicktime" />
    <type extension=".mp4" mimetype="video/mp4" />
    <type extension=".rmvb" mimetype="video/*" />
    <type extension=".wmv" mimetype="video/*" />
    <type extension=".vob" mimetype="video/*" />
    <type extension=".mkv" mimetype="video/*" />
    <type extension=".jar" mimetype="application/java-archive" />
    <type extension=".zip" mimetype="application/zip" />
    <type extension=".rar" mimetype="application/x-rar-compressed" />
    <type extension=".gz" mimetype="application/gzip" />
    <type extension=".gtar" mimetype="application/x-gtar" />
    <type extension=".tar" mimetype="application/x-tar" />
    <type extension=".tgz" mimetype="application/x-compressed" />
    <type extension=".z" mimetype="application/x-compressed" />
    <type extension=".htm" mimetype="text/html" />
    <type extension=".html" mimetype="text/html" />
    <type extension=".php" mimetype="text/php " />
    <type extension=".txt" mimetype="text/plain" />
    <type extension=".c" mimetype="text/plain" />
    <type extension=".conf" mimetype="text/plain" />
    <type extension=".cpp" mimetype="text/plain" />
    <type extension=".h" mimetype="text/plain" />
    <type extension=".java" mimetype="text/plain" />
    <type extension=".log" mimetype="text/plain" />
    <type extension=".prop" mimetype="text/plain" />
    <type extension=".rc" mimetype="text/plain" />
    <type extension=".sh" mimetype="text/plain" />
    <type extension=".csv" mimetype="text/csv" />
    <type extension=".xml" mimetype="text/xml" />
    <type extension=".apk" mimetype="application/vnd.android.package-archive" />
    <type extension=".bin" mimetype="application/octet-stream" />
    <type extension=".class" mimetype="application/octet-stream" />
    <type extension=".exe" mimetype="application/octet-stream" />
    <type extension=".mpc" mimetype="application/vnd.mpohun.certificate" />
    <type extension=".msg" mimetype="application/vnd.ms-outlook" />
    <type extension=".doc" mimetype="application/msword" />
    <type extension=".docx" mimetype="application/msword" />
    <type extension=".js" mimetype="application/x-javascript" />
    <type extension=".pdf" mimetype="application/pdf" />
    <type extension=".pps" mimetype="application/vnd.ms-powerpoint" />
    <type extension=".ppt" mimetype="application/vnd.ms-powerpoint" />
    <type extension=".pptx" mimetype="application/vnd.ms-powerpoint" />
    <type extension=".wps" mimetype="application/vnd.ms-works" />
    <type extension=".rtf" mimetype="application/rtf" />
    <type extension=".xls" mimetype="application/vnd.ms-excel" />
    <type extension=".xlsx" mimetype="application/vnd.ms-excel" />
MimeTypes>


  • 2.代码实现

可直接copy使用,详情请看注释
package com.geely.mars.sqldemo.tools;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.XmlResourceParser;
import android.text.TextUtils;
import com.geely.mars.sqldemo.R;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class MimeTypesTools {

    private static boolean hasLoadMimeType = false;

    /**
     *
     * @param context
     * @param fileName
     * @return 获取文件mime类型
     */
    public static String getMimeType(Context context, String fileName) {
        if (!TextUtils.isEmpty(fileName)) {
            fileName = fileName.toLowerCase();

            MimeTypes mimeTypes = getMimeTypes(context);
            String extension = getSuffix(fileName);
            return mimeTypes.getMimeType(extension);
        }

        return null;
    }

    /**
     * 获取文件格式的后缀名  如 .jpg
     * @param uri 指定文件
     * @return 如 .jpg
     */
    public static String getSuffix(String uri) {
        if (uri == null) {
            return null;
        }

        int dot = uri.lastIndexOf(".");
        if (dot >= 0) {
            return uri.substring(dot);
        } else {
            // No extension.
            return "";
        }
    }

    private static MimeTypes getMimeTypes(Context context) {
        return loadMimeTypes(context);
    }

    /**
     * 解析xml 文件
     * @param context
     * @return
     */
    private static MimeTypes loadMimeTypes(Context context) {
        MimeTypeParser parser = null;
        XmlResourceParser xmlResourceParser = null;
        if (!hasLoadMimeType) {
            try {
                parser = new MimeTypeParser(context, context.getPackageName());
                xmlResourceParser = context.getResources().getXml(R.xml.mimetypes);

                return parser.fromXmlResource(xmlResourceParser);
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            hasLoadMimeType = true;
        }

        return null;
    }
}
package com.geely.mars.sqldemo.tools;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MimeTypeParser {


    public static final String TAG_MIMETYPES = "MimeTypes";
    public static final String TAG_TYPE = "type";

    public static final String ATTR_EXTENSION = "extension";
    public static final String ATTR_MIMETYPE = "mimetype";
    public static final String ATTR_ICON = "icon";

    private XmlPullParser mXpp;
    private MimeTypes mMimeTypes;
    private Resources resources;
    private String packagename;

    public MimeTypeParser(Context ctx, String packagename) throws NameNotFoundException {
        this.packagename = packagename;
        resources = ctx.getPackageManager().getResourcesForApplication(packagename);
    }

    public MimeTypes fromXml(InputStream in)
            throws XmlPullParserException, IOException {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

        mXpp = factory.newPullParser();
        mXpp.setInput(new InputStreamReader(in));

        return parse();
    }

    public MimeTypes fromXmlResource(XmlResourceParser in)
    throws XmlPullParserException, IOException {
        mXpp = in;

        return parse();
    }

    /**
     * 对xml文件的解析
     * @return
     * @throws XmlPullParserException
     * @throws IOException
     */
    public MimeTypes parse()
            throws XmlPullParserException, IOException {

        mMimeTypes = new MimeTypes();

        int eventType = mXpp.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String tag = mXpp.getName();

            if (eventType == XmlPullParser.START_TAG) {
                if (tag.equals(TAG_MIMETYPES)) {

                } else if (tag.equals(TAG_TYPE)) {
                    addMimeTypeStart();
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                if (tag.equals(TAG_MIMETYPES)) {

                }
            }

            eventType = mXpp.next();
        }

        return mMimeTypes;
    }

    private void addMimeTypeStart() {
        String extension = mXpp.getAttributeValue(null, ATTR_EXTENSION);
        String mimetype = mXpp.getAttributeValue(null, ATTR_MIMETYPE);
        String icon = mXpp.getAttributeValue(null, ATTR_ICON);

        if(icon != null){
            int id = resources.getIdentifier(icon.substring(1) , null, packagename);
            if(id > 0){
                mMimeTypes.put(extension, mimetype, id);
                return;
            }
        }

        mMimeTypes.put(extension, mimetype);
    }

}
package com.geely.mars.sqldemo.tools;

import android.webkit.MimeTypeMap;

import java.util.HashMap;
import java.util.Map;

public class MimeTypes {

    private Map mMimeTypes;
    private Map mIcons;

    public MimeTypes() {
        mMimeTypes = new HashMap();
        mIcons = new HashMap();
    }

    /* I think the type and extension names are switched (type contains .png, extension contains x/y),
     * but maybe it's on purpouse, so I won't change it.
     */
    public void put(String type, String extension, int icon){
        put(type, extension);
        mIcons.put(extension, icon);
    }

    public void put(String type, String extension) {
        // Convert extensions to lower case letters for easier comparison
        extension = extension.toLowerCase();

        mMimeTypes.put(type, extension);
    }

    public String getMimeType(String filename) {

        String extension =MimeTypesTools.getExtension(filename);

        // Let's check the official map first. Webkit has a nice extension-to-MIME map.
        // Be sure to remove the first character from the extension, which is the "." character.
        if (extension.length() > 0) {
            String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));

            if (webkitMimeType != null) {
                // Found one. Let's take it!
                return webkitMimeType;
            }
        }

        // Convert extensions to lower case letters for easier comparison
        extension = extension.toLowerCase();

        String mimetype = mMimeTypes.get(extension);

        if(mimetype==null) {
            mimetype = "*/*";
        }

        return mimetype;
    }

    public int getIcon(String mimetype){
        Integer iconResId = mIcons.get(mimetype);
        if(iconResId == null) {
            return 0; // Invalid identifier
        }
        return iconResId;
    }
}

应用

如跳转到支持打开指定文件格式的系统应用

 try {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(android.content.Intent.ACTION_VIEW);
            String type = MimeTypesTools.getMimeType(context, path);
            File file = new File(path);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (file != null) {
                Uri uri = null;
                if (Build.VERSION.SDK_INT >= 24) {

                    uri = FileProvider.getUriForFile(context, context.getPackageName()+".fileprovider", file);
                } else {
                    uri = Uri.fromFile(file);
                }
                if (uri != null) {
                    intent.setDataAndType(uri, type);
                    context.startActivity(intent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show("手机上无可打开此格式的app");

                                      }

你可能感兴趣的:(android)