1. 程式人生 > >Android獲取檔案的mimeType的封裝

Android獲取檔案的mimeType的封裝

概述

MIME(Multipurpose Internet Mail Extensions)多用途網際網路郵件擴充套件型別。是設定某種副檔名的檔案用一種應用程式來開啟的方式型別,當該副檔名檔案被訪問的時候,瀏覽器會自動使用指定應用程式來開啟。多用於指定一些客戶端自定義的檔名,以及一些媒體檔案開啟方式。

步驟


  • 1.定義各種檔案對應的mimeType的xml檔案
在res目錄下面建立一個xml資料夾,在此資料夾下面建立對應xml檔案
<?xml version="1.0" encoding="utf-8"?>
<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<String, String> mMimeTypes;
    private Map<String, Integer> mIcons;

    public MimeTypes() {
        mMimeTypes = new HashMap<String,String>();
        mIcons = new HashMap<String,Integer>();
    }

    /* 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");

                                      }