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:org.mariotaku.twidere.util.SaveImageTask.java

public static File saveImage(final Context context, final File image_file) {
    if (context == null && image_file == null)
        return null;
    try {//from  w  ww  . j  a  va2 s  . c  om
        final String name = image_file.getName();
        if (isEmpty(name))
            return null;
        final String mime_type = getImageMimeType(image_file);
        final MimeTypeMap map = MimeTypeMap.getSingleton();
        final String extension = map.getExtensionFromMimeType(mime_type);
        if (extension == null)
            return null;
        final String name_to_save = name.indexOf(".") != -1 ? name : name + "." + extension;
        final File pub_dir = EnvironmentAccessor
                .getExternalStoragePublicDirectory(EnvironmentAccessor.DIRECTORY_PICTURES);
        if (pub_dir == null)
            return null;
        final File save_dir = new File(pub_dir, "Twidere");
        if (!save_dir.isDirectory() && !save_dir.mkdirs())
            return null;
        final File save_file = new File(save_dir, name_to_save);
        FileUtils.copyFile(image_file, save_file);
        if (save_file != null && mime_type != null) {
            MediaScannerConnectionAccessor.scanFile(context, new String[] { save_file.getPath() },
                    new String[] { mime_type }, null);
        }
        return save_file;
    } catch (final IOException e) {
        Log.w(LOGTAG, "Failed to save file", e);
        return null;
    }
}

From source file:org.mozilla.focus.broadcastreceiver.DownloadBroadcastReceiver.java

private void displaySnackbar(final Context context, long completedDownloadReference,
        DownloadManager downloadManager) {
    if (!isFocusDownload(completedDownloadReference)) {
        return;/*from  w w  w .j av  a  2s  .  co m*/
    }

    final DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(completedDownloadReference);
    try (Cursor cursor = downloadManager.query(query)) {
        if (cursor.moveToFirst()) {
            int statusColumnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(statusColumnIndex)) {
                String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                final String localUri = uriString.startsWith(FILE_SCHEME)
                        ? uriString.substring(FILE_SCHEME.length())
                        : uriString;
                final String fileExtension = MimeTypeMap.getFileExtensionFromUrl(localUri);
                final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
                final String fileName = URLUtil.guessFileName(Uri.decode(localUri), null, mimeType);

                final File file = new File(Uri.decode(localUri));
                final Uri uriForFile = FileProvider.getUriForFile(context,
                        BuildConfig.APPLICATION_ID + FILE_PROVIDER_EXTENSION, file);
                final Intent openFileIntent = IntentUtils.createOpenFileIntent(uriForFile, mimeType);
                showSnackbarForFilename(openFileIntent, context, fileName);
            }
        }
    }
    removeFromHashSet(completedDownloadReference);
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

public static String getMimeType(String url) {
    String type = null;//from   ww  w. j  ava  2s .  c  om
    if (StringUtils.isBlank(url)) {
        return type;
    }
    String extension = null;
    try {
        extension = MimeTypeMap.getFileExtensionFromUrl(URLEncoder.encode(url.replaceAll("\\s*", ""), "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
        Log.e(LOG_NAME, "Unable to determine file extension");
    }

    if (StringUtils.isBlank(extension)) {
        int i = url.lastIndexOf('.');
        if (i > 0 && url.length() >= i + 1) {
            extension = url.substring(i + 1);
        }
    }

    if (!StringUtils.isBlank(extension)) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        type = mime.getMimeTypeFromExtension(extension);
    }
    return type;
}

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

/**
 * This method stores an image, and compresses it in the process so it doesn't fill up the disk. Therefore, do not use
 * it to store an exact copy of the file in question.
 *///from  ww  w. java 2  s .c  om
public boolean internalCreateStoredImage(Context context, String uriString) {
    Uri uri = Uri.parse(uriString);

    ContentResolver resolver = context.getContentResolver();
    String mimeType = resolver.getType(uri);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String extension = mime.getExtensionFromMimeType(mimeType);
    setFileName(uri.getLastPathSegment() + "." + extension);
    setMimeType(mimeType);

    // Create a file to save locally.
    String localFileName = getStoredFileId();
    File localFile = new File(localFileName);

    // Copy the file contents over.
    InputStream is = null;
    CountingOutputStream cos = null;
    try {
        is = new BufferedInputStream(context.getContentResolver().openInputStream(uri));
        cos = new CountingOutputStream(
                new BufferedOutputStream(context.openFileOutput(localFile.getPath(), Context.MODE_PRIVATE)));
        System.gc();
        Bitmap smaller = ImageUtil.createScaledBitmapFromStream(is, MAX_STORED_IMAGE_EDGE,
                MAX_STORED_IMAGE_EDGE, null);
        // TODO: Is JPEG what we want here?
        smaller.compress(Bitmap.CompressFormat.JPEG, 95, cos);
        cos.flush();
        Log.d("Bitmap saved, size = " + (cos.getBytesWritten() / 1024) + "k");
        smaller.recycle();
        System.gc();
    } catch (FileNotFoundException e) {
        Log.e("File not found while storing image.", e);
        return false;
    } catch (Exception e) {
        Log.a("Error storing image.", e);
        return false;
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(cos);
    }

    // Create a StoredFile database entry for this locally saved file.
    StoredFile storedFile = new StoredFile();
    storedFile.setId(getStoredFileId());
    storedFile.setOriginalUri(uri.toString());
    storedFile.setLocalFilePath(localFile.getPath());
    storedFile.setMimeType("image/jpeg");
    FileStore db = ApptentiveDatabase.getInstance(context);
    return db.putStoredFile(storedFile);
}

From source file:com.digitalarx.android.files.FileOperationsHelper.java

public void openFile(OCFile file) {
    if (file != null) {
        String storagePath = file.getStoragePath();
        String encodedStoragePath = WebdavUtils.encodePath(storagePath);

        Intent intentForSavedMimeType = new Intent(Intent.ACTION_VIEW);
        intentForSavedMimeType.setDataAndType(Uri.parse("file://" + encodedStoragePath), file.getMimetype());
        intentForSavedMimeType//from  ww  w. ja  v  a 2 s . c o  m
                .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        Intent intentForGuessedMimeType = null;
        if (storagePath.lastIndexOf('.') >= 0) {
            String guessedMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
            if (guessedMimeType != null && !guessedMimeType.equals(file.getMimetype())) {
                intentForGuessedMimeType = new Intent(Intent.ACTION_VIEW);
                intentForGuessedMimeType.setDataAndType(Uri.parse("file://" + encodedStoragePath),
                        guessedMimeType);
                intentForGuessedMimeType.setFlags(
                        Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        }

        Intent chooserIntent = null;
        if (intentForGuessedMimeType != null) {
            chooserIntent = Intent.createChooser(intentForGuessedMimeType,
                    mFileActivity.getString(R.string.actionbar_open_with));
        } else {
            chooserIntent = Intent.createChooser(intentForSavedMimeType,
                    mFileActivity.getString(R.string.actionbar_open_with));
        }

        mFileActivity.startActivity(chooserIntent);

    } else {
        Log_OC.wtf(TAG, "Trying to open a NULL OCFile");
    }
}

From source file:link.kjr.file_manager.MainActivity.java

public void openfile(String path) {
    Intent i = new Intent();

    String suffix = getSuffix(path);
    if (suffix.equals("zip") || suffix.equals("apk") || suffix.equals("jar")) {
        try {/* w  w w  .j a v a  2  s  .c o  m*/
            decompressZipFile(path);

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        return;
    }

    i.setAction(Intent.ACTION_VIEW);
    String mimetype = MimeTypeMap.getSingleton()
            .getMimeTypeFromExtension(path.substring(path.lastIndexOf(".") + 1, path.length()));
    if (mimetype != null && mimetype.length() > 2) {
        Log.i(BuildConfig.APPLICATION_ID, "mimetype " + mimetype + " for " + path);
        i.setDataAndType(Uri.fromFile(new File(path)), mimetype);
        startActivity(i);
    }

}

From source file:com.zhihu.matisse.MimeType.java

public boolean checkType(ContentResolver resolver, Uri uri) {
    MimeTypeMap map = MimeTypeMap.getSingleton();
    if (uri == null) {
        return false;
    }//from  w  w  w .j  a  va 2s. co m
    String type = map.getExtensionFromMimeType(resolver.getType(uri));
    String path = null;
    // lazy load the path and prevent resolve for multiple times
    boolean pathParsed = false;
    for (String extension : mExtensions) {
        if (extension.equals(type)) {
            return true;
        }
        if (!pathParsed) {
            // we only resolve the path for one time
            path = PhotoMetadataUtils.getPath(resolver, uri);
            if (!TextUtils.isEmpty(path)) {
                path = path.toLowerCase(Locale.US);
            }
            pathParsed = true;
        }
        if (path != null && path.endsWith(extension)) {
            return true;
        }
    }
    return false;
}

From source file:io.nuclei.cyto.share.CytoFileProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    Cursor source = super.query(uri, projection, selection, selectionArgs, sortOrder);
    if (source == null)
        return null;
    try {/*from w  w  w  .j  a va2  s  . c om*/
        final String[] columnNames = source.getColumnNames();

        String[] names = columnNames;
        List<String> missingNames = getMissingColumns(columnNames);
        int mimeTypeIndex = -1;

        if (missingNames.size() > 0) {
            String[] newColumnNames = Arrays.copyOf(columnNames, columnNames.length + missingNames.size());
            int ix = columnNames.length;
            for (String missingName : missingNames) {
                newColumnNames[ix] = missingName;
                if (MediaStore.MediaColumns.MIME_TYPE.equals(missingName))
                    mimeTypeIndex = ix;
                ix++;
            }
            names = newColumnNames;
        }

        MatrixCursor cursor = new MatrixCursor(names, source.getCount());
        source.moveToPosition(-1);
        int columnLength = columnNames.length;
        while (source.moveToNext()) {
            MatrixCursor.RowBuilder row = cursor.newRow();
            for (int i = 0; i < names.length; i++) {
                if (i < columnLength)
                    row.add(source.getString(i));
                else if (i == mimeTypeIndex) {
                    // populate the MIME_TYPE column with a guess as to the mime type of the file
                    final int lastDot = uri.getPath().lastIndexOf('.');
                    if (lastDot >= 0) {
                        String extension = uri.getPath().substring(lastDot + 1);
                        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                        if (mimeType != null)
                            row.add(mimeType);
                        else
                            row.add("application/octet");
                    } else
                        row.add("application/octet");
                } else
                    row.add(null);
            }
        }

        return cursor;
    } finally {
        source.close();
    }
}

From source file:com.utils.note.rteditor.media.choose.processor.MediaProcessor.java

protected String getMimeType() throws IOException, Exception {
    if (mOriginalFile.startsWith("content://")) {
        // ContentProvider file
        ContentResolver resolver = RTApi.getApplicationContext().getContentResolver();
        Uri uri = Uri.parse(mOriginalFile);
        return resolver.getType(uri);
    }/*from  w  ww. j a  v  a  2 s  . c  o  m*/

    String extension = RTFileNameUtils.getExtension(mOriginalFile);
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}

From source file:com.vk.sdk.api.httpClient.VKMultipartEntity.java

protected static String getMimeType(String url) {
    String type = null;/*from  w  ww  .  j  a  v  a 2 s.  c  om*/
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        type = mime.getMimeTypeFromExtension(extension);
    }
    return type;
}