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.owncloud.android.datamodel.OCFile.java

public String getMimeTypeFromName() {
    String extension = "";
    int pos = mRemotePath.lastIndexOf('.');
    if (pos >= 0) {
        extension = mRemotePath.substring(pos + 1);
    }//from   w w w.  ja va 2 s  . c o m
    String result = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
    return (result != null) ? result : "";
}

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  2s. c  om
 */
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:com.owncloud.android.ui.preview.PreviewMediaFragment.java

/**
 * Opens the previewed file with an external application.
 * /*w  ww.j av a2s.  c om*/
 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server, 
 * we should get a list of available apps for MIME tpye in the server and join it with the list of 
 * available apps for the MIME type known from the file extension, to let the user choose
 */
private void openFile() {
    stopPreview(true);
    String storagePath = mFile.getStoragePath();
    String encodedStoragePath = WebdavUtils.encodePath(storagePath);
    try {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mFile.getMimetype());
        i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivity(i);

    } catch (Throwable t) {
        Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: "
                + mFile.getMimetype());
        boolean toastIt = true;
        String mimeType = "";
        try {
            Intent i = new Intent(Intent.ACTION_VIEW);
            mimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
            if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
                if (mimeType != null) {
                    i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mimeType);
                } else {
                    // desperate try
                    i.setDataAndType(Uri.parse("file://" + encodedStoragePath), "*-/*");
                }
                i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivity(i);
                toastIt = false;
            }

        } catch (IndexOutOfBoundsException e) {
            Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);

        } catch (ActivityNotFoundException e) {
            Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType
                    + " obtained from extension");

        } catch (Throwable th) {
            Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);

        } finally {
            if (toastIt) {
                Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(),
                        Toast.LENGTH_SHORT).show();
            }
        }

    }
    finish();
}

From source file:im.neon.adapters.VectorMediasViewerAdapter.java

/**
 * Play a video./*  w  w  w .jav  a2  s.  co m*/
 * @param pageView the pageView
 * @param videoView the video view
 * @param videoUrl the video Url
 * @param videoMimeType the video mimetype
 */
private void playVideo(View pageView, VideoView videoView, String videoUrl, String videoMimeType) {
    // init the video view only if there is a valid file
    // check if the media has been downloaded
    File srcFile = mMediasCache.mediaCacheFile(videoUrl, videoMimeType);

    if ((null != srcFile) && srcFile.exists()) {
        try {
            stopPlayingVideo();
            String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(videoMimeType);

            if (null != extension) {
                extension += "." + extension;
            }

            // copy the media to ensure that it is deleted while playing
            File dstFile = new File(mContext.getCacheDir(), "sliderMedia" + extension);
            if (dstFile.exists()) {
                dstFile.delete();
            }

            // Copy source file to destination
            FileInputStream inputStream = null;
            FileOutputStream outputStream = null;
            try {
                // create only the
                if (!dstFile.exists()) {
                    dstFile.createNewFile();

                    inputStream = new FileInputStream(srcFile);
                    outputStream = new FileOutputStream(dstFile);

                    byte[] buffer = new byte[1024 * 10];
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "## playVideo() : failed " + e.getMessage());
                dstFile = null;
            } finally {
                // Close resources
                try {
                    if (inputStream != null)
                        inputStream.close();
                    if (outputStream != null)
                        outputStream.close();
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## playVideo() : failed " + e.getMessage());
                }
            }

            // update the source
            videoView.setVideoPath(dstFile.getAbsolutePath());
            // hide the thumbnail
            displayVideoThumbnail(pageView, false);

            // let's playing
            mPlayingVideoView = videoView;
            videoView.start();

        } catch (Exception e) {
            Log.e(LOG_TAG, "## playVideo() : videoView.start(); failed " + e.getMessage());
        }
    }
}

From source file:com.stepsdk.android.api.APIClient.java

private MultipartEntity addFile(MultipartEntity mpEntity, String key, String fromPath) throws IOException {

    String filepath;/*from  w  w w  .j  a  va2 s. c o m*/
    try {
        filepath = URLDecoder.decode(fromPath, "UTF-8"); // handle special character
    } catch (Exception e) {
        filepath = fromPath;
    }
    String fromFilename = filepath.substring(filepath.lastIndexOf("/") + 1);

    String filename = "";
    long filesize = 0;
    ContentBody cbFile = null;

    log(TAG, "from upload path: " + fromPath);

    // upload from content uri
    if (fromPath.indexOf("content://") > -1) {
        Uri uri = Uri.parse(fromPath);
        String mime = mContext.getContentResolver().getType(uri);
        String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime);
        String mediatype = mime.substring(0, mime.indexOf('/'));

        InputStream is = mContext.getContentResolver().openInputStream(uri);
        filesize = is.available();
        filename = mediatype + fromFilename + "." + extension;
        cbFile = new InputStreamBody(is, mime, filename);

    } else { //upload from file uri
        File file = new File(filepath);

        filesize = file.length();
        filename = fromFilename;
        cbFile = new FileBody(file, FileUtil.getMimeTypeFromFilePath(fromPath));
    }

    //final String finalfilename = filename;
    final long finalfilesize = filesize;
    //final int task_id = params[1].getIntExtra("cancel_task_id", 0);
    //final Intent cancelintent = params[1];
    //final Intent doneintent = params[2];

    mpEntity.addPart(key, cbFile);

    return mpEntity;
}

From source file:com.karura.framework.plugins.Capture.java

/**
 * Looks up the mime type of a given file name.
 * //from  w w  w.j  a v a 2  s  . c om
 * @param filename
 * @return a mime type
 */
@SuppressLint("DefaultLocale")
public static String getMimeType(String filename) {
    if (filename != null) {
        // Stupid bug in getFileExtensionFromUrl when the file name has a space
        // So we need to replace the space with a url encoded %20
        String url = filename.replace(" ", "%20").toLowerCase();
        MimeTypeMap map = MimeTypeMap.getSingleton();
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension.toLowerCase().equals("3ga")) {
            return AUDIO_3GPP;
        } else {
            return map.getMimeTypeFromExtension(extension);
        }
    } else {
        return "";
    }
}

From source file:com.baasbox.android.BaasFile.java

private Upload uploadRequest(BaasBox box, InputStream stream, int flags, BaasHandler<BaasFile> handler,
        JsonObject acl) {//from   ww w  .java2  s  .  co m
    RequestFactory factory = box.requestFactory;
    if (!isBound.compareAndSet(false, true)) {
        throw new IllegalArgumentException("you cannot upload new content for this file");
    }
    if (stream == null)
        throw new IllegalArgumentException("doStream cannot be null");
    boolean tryGuessExtension = false;
    if (this.mimeType == null) {
        try {
            this.mimeType = URLConnection.guessContentTypeFromStream(stream);
            tryGuessExtension = true;
        } catch (IOException e) {
            this.mimeType = "application/octet-doStream";
        }
    }
    if (this.name == null) {
        this.name = UUID.randomUUID().toString();
        if (tryGuessExtension) {
            String ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);

            if (ext != null) {
                this.name = name + "." + ext;
            }
        }
    }
    String endpoint = factory.getEndpoint("file");
    HttpRequest req = factory.uploadFile(endpoint, true, stream, name, mimeType, acl, attachedData);
    return new Upload(box, this, req, flags, handler);
}

From source file:free.yhc.feeder.model.Utils.java

public static String guessMimeTypeFromUrl(String url) {
    String ext = getExtentionFromUrl(url);
    // NOTE/*w  w  w .  j av  a  2 s  .  c o  m*/
    // "MimeTypeMap.getSingleton().getMimeTypeFromExtension()" doesn't work for
    //   uppercase-extension - ex. MP3.
    // For workaround, converted lowercase is used.
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.toLowerCase());
}

From source file:free.yhc.feeder.model.Utils.java

/**
 * Does given string represents Mime Type?
 * @param str/*from www . ja  v  a2  s .c o m*/
 * @return
 */
public static boolean isMimeType(String str) {
    // Let's reuse Android class
    return MimeTypeMap.getSingleton().hasMimeType(str);
}

From source file:es.ugr.swad.swadroid.modules.downloads.DownloadsManager.java

/**
 * Start an intent to view the file/*ww  w.  j a  v a 2  s .c o m*/
 * @param f The file to view.
 */
private void viewFile(File f) {
    String filenameArray[] = this.chosenNodeName.split("\\.");
    String ext = filenameArray[filenameArray.length - 1];
    String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);

    Intent viewFileIntent = new Intent();
    viewFileIntent.setAction(Intent.ACTION_VIEW);
    viewFileIntent.setDataAndType(Uri.fromFile(f), mime);

    try {
        startActivity(viewFileIntent);
    } catch (ActivityNotFoundException e) {
        showDialog(R.string.errorMsgLaunchingActivity, R.string.errorNoAppForIntent);
    }
}