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:edu.cmu.cylab.starslinger.view.HomeActivity.java

private long getOutStreamSizeAndData(Uri uri, String contentType) throws IOException {

    String name = null;//from   w w w  .  j a v a2 s.  c om
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.DISPLAY_NAME }, null, null,
                null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    name = c.getString(c.getColumnIndex(MediaColumns.DISPLAY_NAME));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    long size = -1;
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.SIZE }, null, null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    size = c.getInt(c.getColumnIndex(MediaColumns.SIZE));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    String data = null;
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.DATA }, null, null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    data = c.getString(c.getColumnIndex(MediaColumns.DATA));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    if (name == null) {
        name = uri.getLastPathSegment();
    }

    File f = null;
    if (size <= 0) {
        String uriString = uri.toString();
        if (uriString.startsWith("file://")) {
            MyLog.v(TAG, uriString.substring("file://".length()));
            f = new File(uriString.substring("file://".length()));
            size = f.length();
        } else {
            MyLog.v(TAG, "not a file: " + uriString);
        }
    }

    ContentResolver cr = getContentResolver();
    InputStream is;
    // read file bytes
    try {
        is = cr.openInputStream(uri);
    } catch (FileNotFoundException e) {
        if (!TextUtils.isEmpty(data)) {
            is = new FileInputStream(data);
        } else {
            return -1; // unable to load file at all
        }
    }

    if ((contentType != null) && (contentType.indexOf('*') != -1)) {
        contentType = getContentResolver().getType(uri);
    }

    if (contentType == null) {
        contentType = URLConnection.guessContentTypeFromStream(is);
        if (contentType == null) {
            String extension = SSUtil.getFileExtensionOnly(name);
            contentType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            if (contentType == null) {
                contentType = SafeSlingerConfig.MIMETYPE_OPEN_ATTACH_DEF;
            }
        }
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[4096];
    while (is.read(buf) > -1) {
        baos.write(buf);
    }
    baos.flush();

    final byte[] fileBytes = baos.toByteArray();
    DraftData d = DraftData.INSTANCE;
    d.setFileData(fileBytes);
    d.setFileSize(fileBytes.length);
    d.setFileType(contentType);
    d.setFileName(name);
    if (f != null && f.exists()) {
        d.setFileDir(f.getAbsolutePath());
    } else if (!TextUtils.isEmpty(data)) {
        d.setFileDir(new File(data).getAbsolutePath());
    }
    return d.getFileSize();
}

From source file:cl.gisred.android.InspActivity.java

private void cerrarFormCrear(boolean bSave, View v, int idR) {
    if (bSave) {/*from  w w  w.j  av a 2  s  .com*/
        if (!validarForm(v)) {
            DialogoConfirmacion oDialog = new DialogoConfirmacion();
            oDialog.show(getFragmentManager(), "tagAlert");
            return;
        } else {

            Resources res = getResources();
            InputStream in_s = res.openRawResource(R.raw.index);
            try {
                View vAction = getLayoutValidate(v);
                byte[] b = new byte[in_s.available()];
                in_s.read(b);
                String sHtml = new String(b);
                HtmlUtils oHtml = new HtmlUtils(getApplicationContext(), sHtml);

                String sValueNumMed = "null";

                for (View view : vAction.getTouchables()) {

                    if (view.getClass().getGenericSuperclass().equals(EditText.class)) {
                        EditText oText = (EditText) view;
                        if (!oText.getText().toString().trim().isEmpty()) {
                            String sMapvalue = HtmlUtils.getMapvalue(oText.getId());
                            String sValorChr = oText.getText().toString();
                            oHtml.setValueById(sMapvalue, "txt", sValorChr);
                            if (oText.getId() == R.id.txtOT) {
                                sValueNumMed = sValorChr;
                            }

                            if (sMapvalue != null && sMapvalue.contains("txt_trabajo_cant")) {
                                try {
                                    double dValue = Double.valueOf(sValorChr);
                                    oHtml.sumHH += dValue;
                                } catch (Exception ex) {
                                    Log.e("Double Convert", "error: " + ex.getMessage());
                                }
                            }
                        }
                    } else if (view.getClass().getGenericSuperclass().equals(CheckBox.class)) {
                        CheckBox oCheck = (CheckBox) view;
                        String sCheck = HtmlUtils.getMapvalue(oCheck.getId());
                        sCheck += oCheck.isChecked() ? "si" : "no";
                        oHtml.setValueById(sCheck, "chk", "");
                    } else if (view.getClass().getGenericSuperclass().equals(Spinner.class)) {
                        Spinner oSpinner = (Spinner) view;
                        oHtml.setValueById(HtmlUtils.getMapvalue(oSpinner.getId()), "txt",
                                oSpinner.getSelectedItem().toString());
                    } else if (view.getClass().getGenericSuperclass().equals(RadioButton.class)) {
                        RadioButton oRadioButton = (RadioButton) view;
                        if (oRadioButton.isChecked()) {
                            String sRadio = HtmlUtils
                                    .getMapvalue(((RadioGroup) oRadioButton.getParent()).getId());
                            sRadio += oRadioButton.getText().toString().toLowerCase().replace(" ", "");
                            oHtml.setValueById(sRadio, "rad", "");
                        }
                    } else if (view.getClass().getGenericSuperclass().equals(ImageView.class)) {
                    }
                }

                //SUMA TOTAL HH
                oHtml.setValueById("txt_trabajo_cant_tot", "txt", "" + oHtml.sumHH);

                //VALIDAR FIRMAS
                if (valImage(vAction, R.id.imgFirmaIns))
                    oHtml.setValueById("firm_prop", "img", String.format("%s.jpg", R.id.imgFirmaIns));
                if (valImage(vAction, R.id.imgFirmaTec))
                    oHtml.setValueById("firm_tecn", "img", String.format("%s.jpg", R.id.imgFirmaTec));

                if (valImage(vAction, R.id.imgPhoto1))
                    oHtml.setValueById("foto_1", "img", "foto1.jpg");
                if (valImage(vAction, R.id.imgPhoto2))
                    oHtml.setValueById("foto_2", "img", "foto2.jpg");
                if (valImage(vAction, R.id.imgPhoto3))
                    oHtml.setValueById("foto_3", "img", "foto3.jpg");

                oHtml.setTitleHtml(sValueNumMed);

                String sHtmlFinal = oHtml.getHtmlFinal();

                //guardar en disco
                oHtml.createHtml(sHtmlFinal);

                //VIA CustomTabs
                /*String url = oHtml.getPathHtml();
                CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
                CustomTabsIntent customTabsIntent = builder.build();
                customTabsIntent.launchUrl(this, Uri.parse(url));*/

                //VIA CHROME scheme
                if (Util.isPackageExisted("com.android.chrome", this)) {
                    String url = oHtml.getPathHtml();

                    File f = new File(url);

                    MimeTypeMap mime = MimeTypeMap.getSingleton();
                    String ext = f.getName().substring(f.getName().lastIndexOf(".") + 1);
                    String type = mime.getMimeTypeFromExtension(ext);

                    Uri uri = Uri.parse("googlechrome://navigate?url=" + url);

                    Intent in = new Intent(Intent.ACTION_VIEW);
                    //in.setDataAndType(uri, "text/html");

                    in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    in.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                    //Uri uriExternal = FileProvider.getUriForFile(getApplicationContext(), "cl.gisred.android", f);

                    in.setDataAndType(uri, type);

                    //startActivity(in);
                    startActivity(Intent.createChooser(in, "Escoja Chrome"));
                } else {
                    Toast.makeText(this, "Debe instalar Chrome, solo preview disponible", Toast.LENGTH_LONG)
                            .show();
                    Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(oHtml.getPathHtml()));
                    startActivity(myIntent);
                }

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

    menuMultipleActions.setVisibility(View.VISIBLE);
    menuInspeccionActions.setVisibility(View.VISIBLE);
    fabShowForm.setVisibility(View.GONE);
    formCrear.dismiss();
}

From source file:com.keylesspalace.tusky.ComposeActivity.java

private void uploadMedia(final QueuedMedia item) {
    item.readyStage = QueuedMedia.ReadyStage.UPLOADING;

    String mimeType = getContentResolver().getType(item.uri);
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String fileExtension = map.getExtensionFromMimeType(mimeType);
    final String filename = String.format("%s_%s_%s.%s", getString(R.string.app_name),
            String.valueOf(new Date().getTime()), StringUtils.randomAlphanumericString(10), fileExtension);

    byte[] content = item.content;

    if (content == null) {
        InputStream stream;//from  w  w  w .j  a  v  a  2 s. co m

        try {
            stream = getContentResolver().openInputStream(item.uri);
        } catch (FileNotFoundException e) {
            Log.d(TAG, Log.getStackTraceString(e));
            return;
        }

        content = MediaUtils.inputStreamGetBytes(stream);
        IOUtils.closeQuietly(stream);

        if (content == null) {
            return;
        }
    }

    if (mimeType == null)
        mimeType = "multipart/form-data";

    item.preview.setProgress(0);

    ProgressRequestBody fileBody = new ProgressRequestBody(content, MediaType.parse(mimeType), false, // If request body logging is enabled, pass true
            new ProgressRequestBody.UploadCallback() { // may reference activity longer than I would like to
                int lastProgress = -1;

                @Override
                public void onProgressUpdate(final int percentage) {
                    if (percentage != lastProgress) {
                        runOnUiThread(() -> item.preview.setProgress(percentage));
                    }
                    lastProgress = percentage;
                }
            });

    MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, fileBody);

    item.uploadRequest = mastodonApi.uploadMedia(body);

    item.uploadRequest.enqueue(new Callback<Attachment>() {
        @Override
        public void onResponse(@NonNull Call<Attachment> call,
                @NonNull retrofit2.Response<Attachment> response) {
            if (response.isSuccessful()) {
                onUploadSuccess(item, response.body());
            } else {
                Log.d(TAG, "Upload request failed. " + response.message());
                onUploadFailure(item, call.isCanceled());
            }
        }

        @Override
        public void onFailure(@NonNull Call<Attachment> call, @NonNull Throwable t) {
            Log.d(TAG, "Upload request failed. " + t.getMessage());
            onUploadFailure(item, call.isCanceled());
        }
    });
}

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.ja v  a2 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);
}

From source file:net.bluehack.ui.MediaActivity.java

private void onItemClick(int index, View view, MessageObject message, int a) {
    if (message == null) {
        return;//from w w  w. j a  va  2 s. c  o  m
    }
    if (actionBar.isActionModeShowed()) {
        int loadIndex = message.getDialogId() == dialog_id ? 0 : 1;
        if (selectedFiles[loadIndex].containsKey(message.getId())) {
            selectedFiles[loadIndex].remove(message.getId());
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount--;
            }
        } else {
            selectedFiles[loadIndex].put(message.getId(), message);
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount++;
            }
        }
        if (selectedFiles[0].isEmpty() && selectedFiles[1].isEmpty()) {
            actionBar.hideActionMode();
        } else {
            selectedMessagesCountTextView.setNumber(selectedFiles[0].size() + selectedFiles[1].size(), true);
        }
        actionBar.createActionMode().getItem(delete)
                .setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
        scrolling = false;
        if (view instanceof SharedDocumentCell) {
            ((SharedDocumentCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        } else if (view instanceof SharedPhotoVideoCell) {
            ((SharedPhotoVideoCell) view).setChecked(a, selectedFiles[loadIndex].containsKey(message.getId()),
                    true);
        } else if (view instanceof SharedLinkCell) {
            ((SharedLinkCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        }
    } else {
        if (selectedMode == 0) {
            PhotoViewer.getInstance().setParentActivity(getParentActivity());
            PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialog_id,
                    mergeDialogId, this);
        } else if (selectedMode == 1 || selectedMode == 4) {
            if (view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                if (cell.isLoaded()) {
                    if (message.isMusic()) {
                        if (MediaController.getInstance().setPlaylist(sharedMediaData[selectedMode].messages,
                                message)) {
                            return;
                        }
                    }
                    File f = null;
                    String fileName = message.messageOwner.media != null
                            ? FileLoader.getAttachFileName(message.getDocument())
                            : "";
                    if (message.messageOwner.attachPath != null
                            && message.messageOwner.attachPath.length() != 0) {
                        f = new File(message.messageOwner.attachPath);
                    }
                    if (f == null || f != null && !f.exists()) {
                        f = FileLoader.getPathToMessage(message.messageOwner);
                    }
                    if (f != null && f.exists()) {
                        String realMimeType = null;
                        try {
                            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) {
                                    realMimeType = message.getDocument().mime_type;
                                    if (realMimeType == null || realMimeType.length() == 0) {
                                        realMimeType = null;
                                    }
                                }
                            }
                            if (Build.VERSION.SDK_INT >= 24) {
                                intent.setDataAndType(
                                        FileProvider.getUriForFile(getParentActivity(),
                                                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 {
                                    getParentActivity().startActivityForResult(intent, 500);
                                } catch (Exception e) {
                                    if (Build.VERSION.SDK_INT >= 24) {
                                        intent.setDataAndType(
                                                FileProvider.getUriForFile(getParentActivity(),
                                                        BuildConfig.APPLICATION_ID + ".provider", f),
                                                "text/plain");
                                    } else {
                                        intent.setDataAndType(Uri.fromFile(f), "text/plain");
                                    }
                                    getParentActivity().startActivityForResult(intent, 500);
                                }
                            } else {
                                getParentActivity().startActivityForResult(intent, 500);
                            }
                        } catch (Exception e) {
                            if (getParentActivity() == null) {
                                return;
                            }
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                            builder.setMessage(LocaleController.formatString("NoHandleAppInstalled",
                                    R.string.NoHandleAppInstalled, message.getDocument().mime_type));
                            showDialog(builder.create());
                        }
                    }
                } else if (!cell.isLoading()) {
                    FileLoader.getInstance().loadFile(cell.getMessage().getDocument(), false, false);
                    cell.updateFileExistIcon();
                } else {
                    FileLoader.getInstance().cancelLoadFile(cell.getMessage().getDocument());
                    cell.updateFileExistIcon();
                }
            }
        } else if (selectedMode == 3) {
            try {
                TLRPC.WebPage webPage = message.messageOwner.media.webpage;
                String link = null;
                if (webPage != null && !(webPage instanceof TLRPC.TL_webPageEmpty)) {
                    if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null
                            && webPage.embed_url.length() != 0) {
                        openWebView(webPage);
                        return;
                    } else {
                        link = webPage.url;
                    }
                }
                if (link == null) {
                    link = ((SharedLinkCell) view).getLink(0);
                }
                if (link != null) {
                    Browser.openUrl(getParentActivity(), link);
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    }
}

From source file:kr.wdream.ui.MediaActivity.java

private void onItemClick(int index, View view, MessageObject message, int a) {
    if (message == null) {
        return;/*w w  w  .  j  a va  2  s.co  m*/
    }
    if (actionBar.isActionModeShowed()) {
        int loadIndex = message.getDialogId() == dialog_id ? 0 : 1;
        if (selectedFiles[loadIndex].containsKey(message.getId())) {
            selectedFiles[loadIndex].remove(message.getId());
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount--;
            }
        } else {
            selectedFiles[loadIndex].put(message.getId(), message);
            if (!message.canDeleteMessage(null)) {
                cantDeleteMessagesCount++;
            }
        }
        if (selectedFiles[0].isEmpty() && selectedFiles[1].isEmpty()) {
            actionBar.hideActionMode();
        } else {
            selectedMessagesCountTextView.setNumber(selectedFiles[0].size() + selectedFiles[1].size(), true);
        }
        actionBar.createActionMode().getItem(delete)
                .setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
        scrolling = false;
        if (view instanceof SharedDocumentCell) {
            ((SharedDocumentCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        } else if (view instanceof SharedPhotoVideoCell) {
            ((SharedPhotoVideoCell) view).setChecked(a, selectedFiles[loadIndex].containsKey(message.getId()),
                    true);
        } else if (view instanceof SharedLinkCell) {
            ((SharedLinkCell) view).setChecked(selectedFiles[loadIndex].containsKey(message.getId()), true);
        }
    } else {
        if (selectedMode == 0) {
            PhotoViewer.getInstance().setParentActivity(getParentActivity());
            PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialog_id,
                    mergeDialogId, this);
        } else if (selectedMode == 1 || selectedMode == 4) {
            if (view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                if (cell.isLoaded()) {
                    if (message.isMusic()) {
                        if (MediaController.getInstance().setPlaylist(sharedMediaData[selectedMode].messages,
                                message)) {
                            return;
                        }
                    }
                    File f = null;
                    String fileName = message.messageOwner.media != null
                            ? FileLoader.getAttachFileName(message.getDocument())
                            : "";
                    if (message.messageOwner.attachPath != null
                            && message.messageOwner.attachPath.length() != 0) {
                        f = new File(message.messageOwner.attachPath);
                    }
                    if (f == null || f != null && !f.exists()) {
                        f = FileLoader.getPathToMessage(message.messageOwner);
                    }
                    if (f != null && f.exists()) {
                        String realMimeType = null;
                        try {
                            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) {
                                    realMimeType = message.getDocument().mime_type;
                                    if (realMimeType == null || realMimeType.length() == 0) {
                                        realMimeType = null;
                                    }
                                }
                            }
                            if (Build.VERSION.SDK_INT >= 24) {
                                intent.setDataAndType(
                                        FileProvider.getUriForFile(getParentActivity(),
                                                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 {
                                    getParentActivity().startActivityForResult(intent, 500);
                                } catch (Exception e) {
                                    if (Build.VERSION.SDK_INT >= 24) {
                                        intent.setDataAndType(
                                                FileProvider.getUriForFile(getParentActivity(),
                                                        BuildConfig.APPLICATION_ID + ".provider", f),
                                                "text/plain");
                                    } else {
                                        intent.setDataAndType(Uri.fromFile(f), "text/plain");
                                    }
                                    getParentActivity().startActivityForResult(intent, 500);
                                }
                            } else {
                                getParentActivity().startActivityForResult(intent, 500);
                            }
                        } catch (Exception e) {
                            if (getParentActivity() == null) {
                                return;
                            }
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setTitle(LocaleController.getString("AppName",
                                    kr.wdream.storyshop.R.string.AppName));
                            builder.setPositiveButton(
                                    LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), null);
                            builder.setMessage(LocaleController.formatString("NoHandleAppInstalled",
                                    kr.wdream.storyshop.R.string.NoHandleAppInstalled,
                                    message.getDocument().mime_type));
                            showDialog(builder.create());
                        }
                    }
                } else if (!cell.isLoading()) {
                    FileLoader.getInstance().loadFile(cell.getMessage().getDocument(), false, false);
                    cell.updateFileExistIcon();
                } else {
                    FileLoader.getInstance().cancelLoadFile(cell.getMessage().getDocument());
                    cell.updateFileExistIcon();
                }
            }
        } else if (selectedMode == 3) {
            try {
                TLRPC.WebPage webPage = message.messageOwner.media.webpage;
                String link = null;
                if (webPage != null && !(webPage instanceof TLRPC.TL_webPageEmpty)) {
                    if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null
                            && webPage.embed_url.length() != 0) {
                        openWebView(webPage);
                        return;
                    } else {
                        link = webPage.url;
                    }
                }
                if (link == null) {
                    link = ((SharedLinkCell) view).getLink(0);
                }
                if (link != null) {
                    Browser.openUrl(getParentActivity(), link);
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    }
}

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

public static void openForView(MessageObject message, Activity activity) throws Exception {
    File f = null;// w  ww  . 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:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * ?MIME Type?.//from w w w .j  a va2  s.  co m
 * 
 * @param path 
 * @return MineType
 */
public String getMIMEType(final String path) {

    // , , ??String?
    String mFilename = new File(path).getName();
    int dotPos = mFilename.lastIndexOf(".");
    String mFormat = mFilename.substring(dotPos, mFilename.length());

    // ??
    String mExt = MimeTypeMap.getFileExtensionFromUrl(mFormat);
    // ???
    mExt = mExt.toLowerCase();
    // MIME Type?
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(mExt);
}

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

public static void openForView(TLObject media, Activity activity) throws Exception {
    if (media == null || activity == null) {
        return;/*from w w w .  j a  va 2s  .  c  o 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.sentaroh.android.SMBExplorer.FileIo.java

private static String isMediaFile(String fp) {
    String mt = null;//  w w  w  .  j  a  v a  2s  . c o  m
    String fid = "";
    if (fp.lastIndexOf(".") > 0) {
        fid = fp.substring(fp.lastIndexOf(".") + 1, fp.length());
        fid = fid.toLowerCase();
    }
    mt = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fid);
    if (mt == null)
        return "";
    else
        return mt;
}