Example usage for android.webkit MimeTypeMap getSingleton

List of usage examples for android.webkit MimeTypeMap getSingleton

Introduction

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

Prototype

public static MimeTypeMap getSingleton() 

Source Link

Document

Get the singleton instance of MimeTypeMap.

Usage

From source file:im.vector.activity.RoomActivity.java

/**
 *
 * @param message/*  w w w  .jav  a2s . c  o  m*/
 * @param mediaUrl
 * @param mediaMimeType
 */
public void createDocument(Message message, final String mediaUrl, final String mediaMimeType) {
    String filename = "MatrixConsole_" + System.currentTimeMillis();

    MimeTypeMap mime = MimeTypeMap.getSingleton();
    filename += "." + mime.getExtensionFromMimeType(mediaMimeType);

    if (message instanceof FileMessage) {
        FileMessage fileMessage = (FileMessage) message;

        if (null != fileMessage.body) {
            filename = fileMessage.body;
        }
    }

    mPendingMediaUrl = mediaUrl;
    mPendingMimeType = mediaMimeType;

    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE)
            .setType(mediaMimeType).putExtra(Intent.EXTRA_TITLE, filename);

    startActivityForResult(intent, CREATE_DOCUMENT);

}

From source file:de.vanita5.twittnuker.util.Utils.java

public static Bitmap.CompressFormat getBitmapCompressFormatByMimetype(final String mimeType,
        final Bitmap.CompressFormat def) {
    final String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
    if ("jpeg".equalsIgnoreCase(extension) || "jpg".equalsIgnoreCase(extension))
        return Bitmap.CompressFormat.JPEG;
    else if ("png".equalsIgnoreCase(extension))
        return Bitmap.CompressFormat.PNG;
    else if ("webp".equalsIgnoreCase(extension))
        return Bitmap.CompressFormat.WEBP;
    return def;//from   ww  w .ja v a 2  s.c  o  m
}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private boolean copyPart(PduPart part, String fallback) {
    Uri uri = part.getDataUri();//from  w  w w .  ja  v a2 s.  c o  m
    String type = new String(part.getContentType());
    boolean isDrm = DrmUtils.isDrmType(type);
    if (isDrm) {
        type = MmsApp.getApplication().getDrmManagerClient().getOriginalMimeType(part.getDataUri());
    }
    if (!ContentType.isImageType(type) && !ContentType.isVideoType(type) && !ContentType.isAudioType(type)) {
        return true; // we only save pictures, videos, and sounds. Skip the text parts,
                     // the app (smil) parts, and other type that we can't handle.
                     // Return true to pretend that we successfully saved the part so
                     // the whole save process will be counted a success.
    }
    InputStream input = null;
    FileOutputStream fout = null;
    try {
        input = mContentResolver.openInputStream(uri);
        if (input instanceof FileInputStream) {
            FileInputStream fin = (FileInputStream) input;

            byte[] location = part.getName();
            if (location == null) {
                location = part.getFilename();
            }
            if (location == null) {
                location = part.getContentLocation();
            }

            String fileName;
            if (location == null) {
                // Use fallback name.
                fileName = fallback;
            } else {
                // For locally captured videos, fileName can end up being something like this:
                //      /mnt/sdcard/Android/data/com.android.mms/cache/.temp1.3gp
                fileName = new String(location);
            }
            File originalFile = new File(fileName);
            fileName = originalFile.getName(); // Strip the full path of where the "part" is
                                               // stored down to just the leaf filename.

            // Depending on the location, there may be an
            // extension already on the name or not. If we've got audio, put the attachment
            // in the Ringtones directory.
            String dir = Environment.getExternalStorageDirectory() + "/"
                    + (ContentType.isAudioType(type) ? Environment.DIRECTORY_RINGTONES
                            : Environment.DIRECTORY_DOWNLOADS)
                    + "/";
            String extension;
            int index;
            if ((index = fileName.lastIndexOf('.')) == -1) {
                extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(type);
            } else {
                extension = fileName.substring(index + 1, fileName.length());
                fileName = fileName.substring(0, index);
            }
            if (isDrm) {
                extension += DrmUtils.getConvertExtension(type);
            }
            // Remove leading periods. The gallery ignores files starting with a period.
            fileName = fileName.replaceAll("^.", "");

            File file = getUniqueDestination(dir + fileName, extension);

            // make sure the path is valid and directories created for this file.
            File parentFile = file.getParentFile();
            if (!parentFile.exists() && !parentFile.mkdirs()) {
                Log.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!");
                return false;
            }

            fout = new FileOutputStream(file);

            byte[] buffer = new byte[8000];
            int size = 0;
            while ((size = fin.read(buffer)) != -1) {
                fout.write(buffer, 0, size);
            }

            // Notify other applications listening to scanner events
            // that a media file has been added to the sd card
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        }
    } catch (IOException e) {
        // Ignore
        Log.e(TAG, "IOException caught while opening or reading stream", e);
        return false;
    } finally {
        if (null != input) {
            try {
                input.close();
            } catch (IOException e) {
                // Ignore
                Log.e(TAG, "IOException caught while closing stream", e);
                return false;
            }
        }
        if (null != fout) {
            try {
                fout.close();
            } catch (IOException e) {
                // Ignore
                Log.e(TAG, "IOException caught while closing stream", e);
                return false;
            }
        }
    }
    return true;
}

From source file:com.android.mms.ui.MessageUtils.java

public static String getContentType(String contentType, String fileName) {
    String finalContentType = "";
    if (contentType == null) {
        return contentType;
    }//from w ww.  j  a v a  2  s  . c o m
    if (contentType.equalsIgnoreCase("application/oct-stream")
            || contentType.equalsIgnoreCase("application/octet-stream")) {
        if (fileName != null) {
            String suffix = fileName.contains(".")
                    ? fileName.substring(fileName.lastIndexOf("."), fileName.length())
                    : "";
            /// M: fix bug ALPS00427229, Ignore suffix Case
            if (suffix.equals("")) {
                return contentType;
            } else if (suffix.equalsIgnoreCase(".bmp")) {
                finalContentType = MmsContentType.IMAGE_BMP;
            } else if (suffix.equalsIgnoreCase(".jpg")) {
                finalContentType = MmsContentType.IMAGE_JPG;
            } else if (suffix.equalsIgnoreCase(".wbmp")) {
                finalContentType = MmsContentType.IMAGE_WBMP;
            } else if (suffix.equalsIgnoreCase(".gif")) {
                finalContentType = MmsContentType.IMAGE_GIF;
            } else if (suffix.equalsIgnoreCase(".png")) {
                finalContentType = MmsContentType.IMAGE_PNG;
            } else if (suffix.equalsIgnoreCase(".jpeg")) {
                finalContentType = MmsContentType.IMAGE_JPEG;
            } else if (suffix.equalsIgnoreCase(".vcs")) {
                finalContentType = MmsContentType.TEXT_VCALENDAR;
            } else if (suffix.equalsIgnoreCase(".vcf")) {
                finalContentType = MmsContentType.TEXT_VCARD;
            } else if (suffix.equalsIgnoreCase(".imy")) {
                finalContentType = MmsContentType.AUDIO_IMELODY;
                // M: fix bug ALPS00355917
            } else if (suffix.equalsIgnoreCase(".ogg")) {
                finalContentType = MmsContentType.AUDIO_OGG;
            } else if (suffix.equalsIgnoreCase(".aac")) {
                finalContentType = MmsContentType.AUDIO_AAC;
            } else if (suffix.equalsIgnoreCase(".mp2")) {
                finalContentType = MmsContentType.AUDIO_MPEG;
                /// M: fix bug ALPS00444328, 3gp audio contentType will be modified
                /// when CMCC send to CU
            } else if (suffix.equalsIgnoreCase(".3gp")) {
                finalContentType = MmsContentType.AUDIO_3GPP;
            } else {
                String extension = fileName.contains(".")
                        ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())
                        : "";
                finalContentType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                if (finalContentType == null) {
                    return contentType;
                }
            }
            return finalContentType;
        }
    }
    return contentType;
}

From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java

private void doLoadAttachment(String path) throws FileNotFoundException {
    File phy = new File(path); // physical
    File vir = new File(path); // virtual, change if needed
    DraftData d = DraftData.INSTANCE;//from w ww . j  av  a2s  .co  m

    try {
        FileInputStream is = new FileInputStream(phy.getAbsolutePath());
        try {
            byte[] outFileData = new byte[is.available()];
            is.read(outFileData);
            d.setFileData(outFileData);
            d.setFileSize(outFileData.length);

            if (d.getFileSize() > SafeSlingerConfig.MAX_FILEBYTES) {
                is.close();
                showNote(String.format(getString(R.string.error_CannotSendFilesOver),
                        SafeSlingerConfig.MAX_FILEBYTES));
                refreshView();
                return;
            }

            String type = URLConnection.guessContentTypeFromStream(is);
            if (type != null)
                d.setFileType(type);
            else {
                String extension = SSUtil.getFileExtensionOnly(vir.getName());
                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                if (type != null) {
                    d.setFileType(type);
                } else {
                    d.setFileType(SafeSlingerConfig.MIMETYPE_OPEN_ATTACH_DEF);
                }
            }
        } finally {
            is.close();
        }
    } catch (OutOfMemoryError e) {
        showNote(R.string.error_OutOfMemoryError);
        refreshView();
        return;
    } catch (IOException e) {
        showNote(e);
        refreshView();
        return;
    }
    d.setFileName(vir.getName());
    d.setFileDir(phy.getPath());
    d.setMsgHash(null);
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void startLocalFileViewerIntent(FileListItem item) {
    String mt = null, fid = null;
    sendDebugLogMsg(1, "I", "Start Intent: name=" + item.getName());
    if (item.getName().lastIndexOf(".") > 0) {
        fid = item.getName().substring(item.getName().lastIndexOf(".") + 1, item.getName().length());
        fid = fid.toLowerCase();/* w w  w  . j a  v  a 2  s. c om*/
    }
    mt = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fid);
    if (mt == null && fid != null && fid.equals("log"))
        mt = "text/plain";
    if (mt != null) {
        if (mt.startsWith("text"))
            mt = "text/plain";
        try {
            Intent intent;
            intent = new Intent(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + item.getPath() + "/" + item.getName()), mt);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            //            commonDlg.showCommonDialog(false,"E", "File viewer can not be found.",
            //                  "File name="+item.getName()+", MimeType="+mt,null);
            showDialogMsg("E", "File viewer can not be found.",
                    "File name=" + item.getName() + ", MimeType=" + mt);
        }
    } else {
        //         commonDlg.showCommonDialog(false,"E", "MIME type can not be found.",
        //               "File name="+item.getName(),null);
        showDialogMsg("E", "MIME type can not be found.", "File name=" + item.getName());
    }
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void startRemoteFileViewerIntent(FileListAdapter fla, final FileListItem item) {
    String fid = null;//  w  ww  .  j  a va 2s.  c om
    sendDebugLogMsg(1, "I", "Start Intent: name=" + item.getName());
    if (item.getName().lastIndexOf(".") > 0) {
        fid = item.getName().substring(item.getName().lastIndexOf(".") + 1, item.getName().length());
        fid = fid.toLowerCase();
    }
    String mtx = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fid);
    if (mtx == null && fid != null && fid.equals("log"))
        mtx = "text/plain";

    if (mtx != null) {
        if (mtx.startsWith("text"))
            mtx = "text/plain";
        final String mt = mtx;
        NotifyEvent ntfy = new NotifyEvent(this);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            public void positiveResponse(Context c, Object[] o) {
                //               Log.v("","positive");
                try {
                    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse(
                            "file://" + mGp.SMBExplorerRootDir + "/SMBExplorer/download/" + item.getName()),
                            mt);
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    //                  commonDlg.showCommonDialog(false,"E", "File viewer can not be found.",
                    //                        "File name="+item.getName()+", MimeType="+mt,null);
                    showDialogMsg("E", "File viewer can not be found.",
                            "File name=" + item.getName() + ", MimeType=" + mt);
                }
            }

            @Override
            public void negativeResponse(Context c, Object[] o) {
                //               Log.v("","negative");
            }
        });
        downloadRemoteFile(fla, item, remoteBase, ntfy);
    } else {
        //         commonDlg.showCommonDialog(false,"E", "MIME type can not be found.",
        //               "File name="+item.getName(),null);
        showDialogMsg("E", "MIME type can not be found.", "File name=" + item.getName());
    }

}

From source file:com.codename1.impl.android.AndroidImplementation.java

private String getMimeType(String url) {
    String type = null;/*ww w .  j  a va 2  s.c  om*/
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();

        type = mime.getMimeTypeFromExtension(extension);
    }
    if (type == null) {
        try {
            Uri uri = Uri.parse(url);
            ContentResolver cr = getContext().getContentResolver();
            type = cr.getType(uri);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    return type;
}

From source file:org.telegram.ui.ChatActivity.java

@Override
public void didSelectFile(DocumentSelectActivity activity, String path, String name, String ext, long size) {
    activity.finishFragment();/*from w  w w . jav  a2  s  . c om*/
    TLRPC.TL_document document = new TLRPC.TL_document();
    document.thumb = new TLRPC.TL_photoSizeEmpty();
    document.thumb.type = "s";
    document.id = 0;
    document.user_id = UserConfig.clientUserId;
    document.date = ConnectionsManager.Instance.getCurrentTime();
    document.file_name = name;
    document.size = (int) size;
    document.dc_id = 0;
    document.path = path;
    if (ext.length() != 0) {
        MimeTypeMap myMime = MimeTypeMap.getSingleton();
        String mimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
        if (mimeType != null) {
            document.mime_type = mimeType;
        } else {
            document.mime_type = "application/octet-stream";
        }
    } else {
        document.mime_type = "application/octet-stream";
    }
    MessagesController.Instance.sendMessage(document, dialog_id);
}