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:com.github.fi3te.iliasdownloader.controller.Util.java

public static void openFile(File file, Activity forMessages) {
    if (file != null && forMessages != null && file.isFile()) {
        String extension = FilenameUtils.getExtension(file.getPath());
        if (extension.length() > 0) {
            try {
                extension = extension.toLowerCase();
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file),
                        MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                forMessages.startActivity(intent);
            } catch (ActivityNotFoundException anfe) {
                Toast.makeText(forMessages, forMessages.getResources().getString(R.string.unknown_type),
                        Toast.LENGTH_SHORT).show();
            }//from  w w  w  .j  ava  2s.co m
        }
    }
}

From source file:org.opensilk.music.library.mediastore.util.FilesUtil.java

public static String guessMimeType(String ext) {
    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
    if (mimeType == null) {
        mimeType = "*/*";
    }/* w w w . j  a v a 2  s.com*/
    return mimeType;
}

From source file:Main.java

/**
 * Helper to convert unknown or unmapped attachments to something useful based on filename
 * extensions. The mime type is inferred based upon the table below. It's not perfect, but
 * it helps./*from w w  w . j  av  a 2s. com*/
 *
 * <pre>
 *                   |---------------------------------------------------------|
 *                   |                  E X T E N S I O N                      |
 *                   |---------------------------------------------------------|
 *                   | .eml        | known(.png) | unknown(.abc) | none        |
 * | M |-----------------------------------------------------------------------|
 * | I | none        | msg/rfc822  | image/png   | app/abc       | app/oct-str |
 * | M |-------------| (always     |             |               |             |
 * | E | app/oct-str |  overrides  |             |               |             |
 * | T |-------------|             |             |-----------------------------|
 * | Y | text/plain  |             |             | text/plain                  |
 * | P |-------------|             |-------------------------------------------|
 * | E | any/type    |             | any/type                                  |
 * |---|-----------------------------------------------------------------------|
 * </pre>
 *
 * NOTE: Since mime types on Android are case-*sensitive*, return values are always in
 * lower case.
 *
 * @param fileName The given filename
 * @param mimeType The given mime type
 * @return A likely mime type for the attachment
 */
public static String inferMimeType(final String fileName, final String mimeType) {
    String resultType = null;
    String fileExtension = getFilenameExtension(fileName);
    boolean isTextPlain = "text/plain".equalsIgnoreCase(mimeType);

    if ("eml".equals(fileExtension)) {
        resultType = "message/rfc822";
    } else {
        boolean isGenericType = isTextPlain || "application/octet-stream".equalsIgnoreCase(mimeType);
        // If the given mime type is non-empty and non-generic, return it
        if (isGenericType || TextUtils.isEmpty(mimeType)) {
            if (!TextUtils.isEmpty(fileExtension)) {
                // Otherwise, try to find a mime type based upon the file extension
                resultType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
                if (TextUtils.isEmpty(resultType)) {
                    // Finally, if original mimetype is text/plain, use it; otherwise synthesize
                    resultType = isTextPlain ? mimeType : "application/" + fileExtension;
                }
            }
        } else {
            resultType = mimeType;
        }
    }

    // No good guess could be made; use an appropriate generic type
    if (TextUtils.isEmpty(resultType)) {
        resultType = isTextPlain ? "text/plain" : "application/octet-stream";
    }
    return resultType.toLowerCase();
}

From source file:org.mariotaku.twidere.util.SaveFileTask.java

public static File saveFile(final Context context, final File source, final String mimeType,
        final File destination) {
    if (context == null && source == null)
        return null;
    Source ioSrc = null;// w  w w  .  ja  v  a2 s.  c  om
    BufferedSink sink = null;
    try {
        final String name = source.getName();
        if (isEmpty(name))
            return null;
        final MimeTypeMap map = MimeTypeMap.getSingleton();
        final String extension = map.getExtensionFromMimeType(mimeType);
        if (extension == null)
            return null;
        final String nameToSave = getFileNameWithExtension(name, extension);
        if (!destination.isDirectory() && !destination.mkdirs())
            return null;
        final File saveFile = new File(destination, nameToSave);
        ioSrc = Okio.source(source);
        sink = Okio.buffer(Okio.sink(saveFile));
        sink.writeAll(ioSrc);
        sink.flush();
        if (mimeType != null) {
            MediaScannerConnection.scanFile(context, new String[] { saveFile.getPath() },
                    new String[] { mimeType }, null);
        }
        return saveFile;
    } catch (final IOException e) {
        final int errno = Utils.getErrorNo(e.getCause());
        Log.w(LOGTAG, "Failed to save file", e);
        return null;
    } finally {
        Utils.closeSilently(sink);
        Utils.closeSilently(ioSrc);
    }
}

From source file:com.github.vase4kin.teamcityapp.artifact.router.ArtifactRouterImpl.java

/**
 * {@inheritDoc}/*from  w w  w.  j  a v a  2 s .co m*/
 */
@Override
public void startFileActivity(File file) {
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
    String type = map.getMimeTypeFromExtension(ext);

    if (type == null) {
        type = ALL_FILES_TYPE;
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri data = FileProvider.getUriForFile(mActivity, BuildConfig.APPLICATION_ID + ".provider", file);
    intent.setDataAndType(data, type);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    //User couldn't have app with type intent
    try {
        mActivity.startActivity(intent);
    } catch (android.content.ActivityNotFoundException e) {
        intent.setDataAndType(data, ALL_FILES_TYPE);
        mActivity.startActivity(intent);
    }
}

From source file:org.zywx.wbpalmstar.engine.EDownloadDialog.java

private void init(String inUrl) {
    url = inUrl;//from   w  ww  . j a v  a2s .  c  om
    String suffix = makeFileSuffix(url);
    MimeTypeMap mtm = MimeTypeMap.getSingleton();
    mimetype = mtm.getMimeTypeFromExtension(suffix);
    if (null == mimetype) {

    }
    setProgress(0);
    setIcon(EResources.icon);
    setCancelable(false);
    setTitle("");
    setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    setMax(100);
    setButton("?", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            mFromStop = true;
            stopDownload();
        }
    });
}

From source file:com.slownet5.pgprootexplorer.utils.FileUtils.java

public static String getMimeType(String filename) {
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(FileUtils.getExtension(filename));

}

From source file:me.kartikarora.transfersh.activities.DownloadActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_download);

    final CoordinatorLayout layout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
    Intent intent = getIntent();/*from w  w  w .  j  av  a2 s.  c  o  m*/
    url = intent.getData().toString();
    name = FilenameUtils.getName(url);
    type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
    TransferApplication application = (TransferApplication) getApplication();
    mTracker = application.getDefaultTracker();

    new AlertDialog.Builder(DownloadActivity.this)
            .setMessage(getString(R.string.download_file) + " " + getString(R.string.app_name) + "?")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    checkForDownload(name, type, url, layout);
                    finish();
                }
            }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            }).create().show();

    mTracker.send(new HitBuilders.EventBuilder().setCategory("Activity : " + this.getClass().getSimpleName())
            .setAction("Launched").build());

}

From source file:com.mobileuni.helpers.FileManager.java

public void UploadToUrl(String siteUrl, String token, String filepath) {

    String url = siteUrl + "/webservice/upload.php?token=" + token;
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    org.apache.http.client.methods.HttpPost httppost = new org.apache.http.client.methods.HttpPost(url);
    File file = new File(filepath);

    String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
            MimeTypeMap.getFileExtensionFromUrl(filepath.substring(filepath.lastIndexOf("."))));

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, mimetype);
    mpEntity.addPart("userfile", cbFile);

    httppost.setEntity(mpEntity);/*from  w  ww  .jav  a 2 s.  c o m*/
    Log.d(TAG, "upload executing request " + httppost.getRequestLine());
    try {

        HttpResponse response = httpclient.execute(httppost);

        HttpEntity resEntity = response.getEntity();

        Log.d(TAG, "upload line status " + response.getStatusLine());
        if (resEntity != null) {
            Log.d(TAG, "upload " + EntityUtils.toString(resEntity));
            //JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
        } else {
            Log.d(TAG, "upload error: " + EntityUtils.toString(resEntity));
        }

    } catch (Exception ex) {
        Log.d(TAG, "Error: " + ex);
    }

    httpclient.getConnectionManager().shutdown();
}

From source file:de.yaacc.util.FileDownloader.java

@Override
protected Void doInBackground(DIDLObject... didlObjects) {
    if (didlObjects == null || didlObjects.length == 0 || didlObjects.length > 1) {
        throw new IllegalStateException("to less or many didlObjects....");
    }/*from ww  w .j a  v  a2s .  co  m*/
    if (!isExternalStorageWritable()) {
        throw new IllegalStateException("External Storage is not writeable");
    }

    try {
        File storageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/yaacc");
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        createNotification(storageDir.getAbsolutePath());
        List<Item> items = upnpClient.toItemList(didlObjects[0]);
        for (Item item : items) {
            PlayableItem playableItem = new PlayableItem(item, 0);
            String filename = playableItem.getTitle().replace(" ", "");
            filename += "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(playableItem.getMimeType());
            File file = new File(storageDir, filename);
            if (file.exists()) {
                int i = 1;
                while (file.exists()) {
                    filename = playableItem.getTitle().replace(" ", "") + "_" + i;
                    filename += "."
                            + MimeTypeMap.getSingleton().getExtensionFromMimeType(playableItem.getMimeType());
                    file = new File(storageDir, filename);
                    i++;
                }
            }

            try {

                InputStream is = new URL(playableItem.getUri().toString()).openStream();
                FileOutputStream outputStream = new FileOutputStream(file);
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = is.read(b)) != -1) {
                    outputStream.write(b, 0, len);
                }
                is.close();
                outputStream.close();

            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    } finally {
        cancleNotification();
    }
    return null;
}