Example usage for android.webkit MimeTypeMap getMimeTypeFromExtension

List of usage examples for android.webkit MimeTypeMap getMimeTypeFromExtension

Introduction

In this page you can find the example usage for android.webkit MimeTypeMap getMimeTypeFromExtension.

Prototype

@Nullable
public String getMimeTypeFromExtension(String extension) 

Source Link

Document

Return the MIME type for the given extension.

Usage

From source file:com.apptentive.android.sdk.model.FileMessage.java

public boolean createStoredFile(Context context, String uriString) {
    Uri uri = Uri.parse(uriString);/*w  w w .  j  a v  a2s  . co m*/

    ContentResolver resolver = context.getContentResolver();
    String mimeType = resolver.getType(uri);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String extension = mime.getExtensionFromMimeType(mimeType);

    // If we can't get the mime type from the uri, try getting it from the extension.
    if (extension == null) {
        extension = MimeTypeMap.getFileExtensionFromUrl(uriString);
    }
    if (mimeType == null && extension != null) {
        mimeType = mime.getMimeTypeFromExtension(extension);
    }

    setFileName(uri.getLastPathSegment() + "." + extension);
    setMimeType(mimeType);

    InputStream is = null;
    try {
        is = new BufferedInputStream(context.getContentResolver().openInputStream(uri));
        return createStoredFile(context, is, mimeType);
    } catch (FileNotFoundException e) {
        Log.e("File not found while storing file.", e);
    } catch (IOException e) {
        Log.a("Error storing image.", e);
    } finally {
        Util.ensureClosed(is);
    }
    return false;
}

From source file:eu.codeplumbers.cosi.activities.CozyActivity.java

@Override
public void onListFragmentInteraction(File file) {
    if (currentFragment instanceof FileManagerFragment) {
        if (!file.isFile()) {
            String path = file.getPath().equals("") ? "/" : file.getPath() + "/";
            ((FileManagerFragment) currentFragment).setCurrentPath(path + file.getName());
            ((FileManagerFragment) currentFragment).refreshList();
        } else {//from  w  w w. j  a v a2s  . com
            if (file.getDownloaded()) {
                MimeTypeMap myMime = MimeTypeMap.getSingleton();
                Intent newIntent = new Intent(Intent.ACTION_VIEW);
                String mimeType = myMime
                        .getMimeTypeFromExtension(FileUtils.fileExt(file.getName()).substring(1));
                newIntent.setDataAndType(Uri.fromFile(file.getLocalPath()), mimeType);
                newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    startActivity(newIntent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(this, "No handler for this type of file.", Toast.LENGTH_LONG).show();
                }
            } else {
                Intent intent = new Intent(CozyActivity.this, CosiFileDownloadService.class);
                ArrayList<String> arrayList = new ArrayList<String>();
                arrayList.add(0, file.getId() + "");
                intent.putStringArrayListExtra("fileToDownload", arrayList);
                startService(intent);
            }
        }
    }
}

From source file:br.com.anteros.vendas.gui.AnexoCadastroActivity.java

/**
 * Abre o anexo pela URI do arquivo anexado para visualizao.
 * @param mUri//from   w  w  w .j a v a 2  s.co  m
 */
private void abrirAnexo(Uri mUri) {
    String extension = FilenameUtils.getExtension(AndroidFileUtils.getPath(AnexoCadastroActivity.this, mUri));
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        MimeTypeMap mime = MimeTypeMap.getSingleton();

        String type = mime.getMimeTypeFromExtension(extension);

        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(mUri, type);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplicationContext().startActivity(intent);

    } catch (ActivityNotFoundException e) {
        new ErrorAlert(AnexoCadastroActivity.this, getResources().getString(R.string.app_name),
                "No foi encontrado nenhum aplicativo nesse aparelho que suporte abrir a extenso '"
                        + extension
                        + "', entre em contato com a equipe de Suporte para resolver esse problema.").show();
    } catch (Exception e) {
        new ErrorAlert(AnexoCadastroActivity.this, getResources().getString(R.string.app_name),
                "No foi possvel abrir o anexo " + anexo.getId() + ". " + e.getMessage()).show();
        e.printStackTrace();
    }
}

From source file:mobisocial.musubi.util.UriImage.java

private void initFromFile(Context context, Uri uri) {
    mPath = uri.getPath();//from w  w  w  .  j ava 2 s  .co  m
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String extension = MimeTypeMap.getFileExtensionFromUrl(mPath);
    if (TextUtils.isEmpty(extension)) {
        // getMimeTypeFromExtension() doesn't handle spaces in filenames nor can it handle
        // urlEncoded strings. Let's try one last time at finding the extension.
        int dotPos = mPath.lastIndexOf('.');
        if (0 <= dotPos) {
            extension = mPath.substring(dotPos + 1);
        }
    }
    mContentType = mimeTypeMap.getMimeTypeFromExtension(extension);
    // It's ok if mContentType is null. Eventually we'll show a toast telling the
    // user the picture couldn't be attached.
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static void openForView(TLObject media, Activity activity) throws Exception {
    if (media == null || activity == null) {
        return;/*w  ww  .  j a v a2 s .co  m*/
    }
    String fileName = FileLoader.getAttachFileName(media);
    File f = FileLoader.getPathToAttach(media, true);
    if (f != null && f.exists()) {
        String realMimeType = null;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        MimeTypeMap myMime = MimeTypeMap.getSingleton();
        int idx = fileName.lastIndexOf('.');
        if (idx != -1) {
            String ext = fileName.substring(idx + 1);
            realMimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
            if (realMimeType == null) {
                if (media instanceof TLRPC.TL_document) {
                    realMimeType = ((TLRPC.TL_document) media).mime_type;
                }
                if (realMimeType == null || realMimeType.length() == 0) {
                    realMimeType = null;
                }
            }
        }
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setDataAndType(
                    FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", f),
                    realMimeType != null ? realMimeType : "text/plain");
        } else {
            intent.setDataAndType(Uri.fromFile(f), realMimeType != null ? realMimeType : "text/plain");
        }
        if (realMimeType != null) {
            try {
                activity.startActivityForResult(intent, 500);
            } catch (Exception e) {
                if (Build.VERSION.SDK_INT >= 24) {
                    intent.setDataAndType(
                            FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", f),
                            "text/plain");
                } else {
                    intent.setDataAndType(Uri.fromFile(f), "text/plain");
                }
                activity.startActivityForResult(intent, 500);
            }
        } else {
            activity.startActivityForResult(intent, 500);
        }
    }
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static void openForView(MessageObject message, Activity activity) throws Exception {
    File f = null;//from ww  w  . j a  v a  2s.  c o m
    String fileName = message.getFileName();
    if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) {
        f = new File(message.messageOwner.attachPath);
    }
    if (f == null || !f.exists()) {
        f = FileLoader.getPathToMessage(message.messageOwner);
    }
    if (f != null && f.exists()) {
        String realMimeType = null;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        MimeTypeMap myMime = MimeTypeMap.getSingleton();
        int idx = fileName.lastIndexOf('.');
        if (idx != -1) {
            String ext = fileName.substring(idx + 1);
            realMimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
            if (realMimeType == null) {
                if (message.type == 9 || message.type == 0) {
                    realMimeType = message.getDocument().mime_type;
                }
                if (realMimeType == null || realMimeType.length() == 0) {
                    realMimeType = null;
                }
            }
        }
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setDataAndType(
                    FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", f),
                    realMimeType != null ? realMimeType : "text/plain");
        } else {
            intent.setDataAndType(Uri.fromFile(f), realMimeType != null ? realMimeType : "text/plain");
        }
        if (realMimeType != null) {
            try {
                activity.startActivityForResult(intent, 500);
            } catch (Exception e) {
                if (Build.VERSION.SDK_INT >= 24) {
                    intent.setDataAndType(
                            FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", f),
                            "text/plain");
                } else {
                    intent.setDataAndType(Uri.fromFile(f), "text/plain");
                }
                activity.startActivityForResult(intent, 500);
            }
        } else {
            activity.startActivityForResult(intent, 500);
        }
    }
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private void startUpdateApk(Uri installerUri) {
    MimeTypeMap myMime = MimeTypeMap.getSingleton();
    String mimeType = myMime.getMimeTypeFromExtension("apk");
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(installerUri, mimeType);//"application/vnd.android.package-archive");
    context.startActivity(intent);/*from  w ww  . jav  a  2 s . c  o  m*/
}

From source file:com.example.commander.CommandManager.java

/**
 *    Start intent for file open/*from  w  ww.  j av a 2s  .c  o m*/
 */
private void StartOpenFileIntent() {
    // Make intent
    File file = new File(mFilePath);
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String extension = MimeTypeMap.getFileExtensionFromUrl(file.getName());
    String type = map.getMimeTypeFromExtension(extension);
    if (type == null) {
        type = "*/*";
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri dataForIntent = Uri.fromFile(file);
    intent.setDataAndType(dataForIntent, type);
    mActivity.startActivity(intent);
}

From source file:com.doplgangr.secrecy.views.FileViewer.java

void sendMultiple(final ArrayList<FilesListFragment.DecryptArgHolder> args) {
    new Thread(new Runnable() {
        @Override//from ww w . j a v a2s  .c om
        public void run() {
            ArrayList<Uri> uris = new ArrayList<Uri>();
            Set<String> mimes = new HashSet<String>();
            MimeTypeMap myMime = MimeTypeMap.getSingleton();
            for (FilesListFragment.DecryptArgHolder arg : args) {
                File tempFile = getFile(arg.encryptedFile, arg.onFinish);
                //File specified is not invalid
                if (tempFile != null) {
                    if (tempFile.getParentFile().equals(Storage.getTempFolder()))
                        tempFile = new java.io.File(Storage.getTempFolder(), tempFile.getName());
                    uris.add(OurFileProvider.getUriForFile(context, OurFileProvider.FILE_PROVIDER_AUTHORITY,
                            tempFile));
                    mimes.add(myMime.getMimeTypeFromExtension(arg.encryptedFile.getType()));

                }
            }
            if (uris.size() == 0 || mimes.size() == 0)
                return;
            Intent newIntent;
            if (uris.size() == 1) {
                newIntent = new Intent(Intent.ACTION_SEND);
                newIntent.putExtra(Intent.EXTRA_STREAM, uris.get(0));
            } else {
                newIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                newIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
            }
            if (mimes.size() > 1)
                newIntent.setType("text/plain"); //Mixed filetypes
            else
                newIntent.setType(new ArrayList<String>(mimes).get(0));
            newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            Intent chooserIntent = generateCustomChooserIntent(newIntent, uris);
            try {
                startActivity(Intent.createChooser(chooserIntent,
                        CustomApp.context.getString(R.string.Dialog__send_file)));
                FilesActivity.onPauseDecision.startActivity();
            } catch (android.content.ActivityNotFoundException e) {
                Util.toast(context, CustomApp.context.getString(R.string.Error__no_activity_view),
                        Toast.LENGTH_LONG);
                FilesActivity.onPauseDecision.finishActivity();
            }
        }
    }).start();
}

From source file:org.mozilla.gecko.GeckoAppShell.java

private static Drawable getDrawableForExtension(PackageManager pm, String aExt) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    MimeTypeMap mtm = MimeTypeMap.getSingleton();
    String mimeType = mtm.getMimeTypeFromExtension(aExt);
    if (mimeType != null && mimeType.length() > 0)
        intent.setType(mimeType);/*from  w w w  .j  a  va2  s  .  c o m*/
    else
        return null;

    List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
    if (list.size() == 0)
        return null;

    ResolveInfo resolveInfo = list.get(0);

    if (resolveInfo == null)
        return null;

    ActivityInfo activityInfo = resolveInfo.activityInfo;

    return activityInfo.loadIcon(pm);
}