开发者

Right mimeType for opening file

I'm trying to open a File with an Intent, but Android doesn't open the right application for the filetype.

Using the following code, every file - pdf, images, everything - is opened with the music app:

Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.fromFile(file));
startActivity(i);

When I manually specify the mimeType, the right application is opened 开发者_StackOverflow中文版- in this case the pictureviewer.

i.setDataAndType(Uri.fromFile(file), "image/*");

Is there any way to get Android to open the right application, instead of manually setting the type judging from the file's extension?


You could do something like this:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.fromFile(file));
intent.setType(FileHelper.getMimeType(file));
startActivity(intent);

Here is (the relevant part of) my helper class to get mimeType from file.

The key is to use MimeTypeMap

public class FileHelper
{

    public static String getMimeType(File file)
    {
        return getMimeType(file.getName());
    }

    public static String getMimeType(String fileName)
    {
        String extension = getExtension(fileName);
        if (extension == null)
            return null;
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }

    public static String getExtension(File file)
    {
        return getExtension(file.getName());
    }

    public static String getExtension(String fileName)
    {
        int extensionDelimiter = fileName.lastIndexOf(".");
        if (extensionDelimiter == -1)
            return null;
        return fileName.substring(extensionDelimiter + 1, fileName.length());
    }
}

Hope this helps.


That depends on the other applications. If they have set their intent filters including mime information, file extension information or both. So, my recommendation is you can't rely on other applications, so the best option is to provide as much info as possible when you launch an intent, including MIME type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜