Example usage for android.content Intent setDataAndType

List of usage examples for android.content Intent setDataAndType

Introduction

In this page you can find the example usage for android.content Intent setDataAndType.

Prototype

public @NonNull Intent setDataAndType(@Nullable Uri data, @Nullable String type) 

Source Link

Document

(Usually optional) Set the data for the intent along with an explicit MIME data type.

Usage

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

public static void openForView(MessageObject message, Activity activity) throws Exception {
    File f = null;//  w  w w . j  a  v a 2 s . 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:com.android.contacts.activities.DialtactsActivity.java

private void fixIntent(Intent intent) {
    // This should be cleaned up: the call key used to send an Intent
    // that just said to go to the recent calls list.  It now sends this
    // abstract action, but this class hasn't been rewritten to deal with it.
    if (Intent.ACTION_CALL_BUTTON.equals(intent.getAction())) {
        intent.setDataAndType(Calls.CONTENT_URI, Calls.CONTENT_TYPE);
        intent.putExtra("call_key", true);
        setIntent(intent);/*from  w w w . j  a  va2 s  .c  o m*/
    }
}

From source file:com.amaze.filemanager.fragments.Main.java

private void launch(final SmbFile smbFile, final long si) {
    s = Streamer.getInstance();/*from   w ww  .  j av a2 s . c  om*/
    new Thread() {
        public void run() {
            try {
                s.setStreamSrc(smbFile, null, si);//the second argument can be a list of subtitle files
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            Uri uri = Uri.parse(Streamer.URL
                                    + Uri.fromFile(new File(Uri.parse(smbFile.getPath()).getPath()))
                                            .getEncodedPath());
                            Intent i = new Intent(Intent.ACTION_VIEW);
                            i.setDataAndType(uri, MimeTypes.getMimeType(new File(smbFile.getPath())));
                            PackageManager packageManager = getActivity().getPackageManager();
                            List<ResolveInfo> resInfos = packageManager.queryIntentActivities(i, 0);
                            if (resInfos != null && resInfos.size() > 0)
                                startActivity(i);
                            else
                                Toast.makeText(getActivity(),
                                        "You will need to copy this file to storage to open it",
                                        Toast.LENGTH_SHORT).show();
                        } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
}

From source file:com.dawsonloudon.videoplayer.VideoPlayer.java

private void playVideo(String url) throws IOException {
    if (url.contains("bit.ly/") || url.contains("goo.gl/") || url.contains("tinyurl.com/")
            || url.contains("youtu.be/")) {
        //support for google / bitly / tinyurl / youtube shortens
        URLConnection con = new URL(url).openConnection();
        con.connect();//from  w w w . j  av a  2  s .  c  o m
        InputStream is = con.getInputStream();
        //new redirected url
        url = con.getURL().toString();
        is.close();
    }

    // Create URI
    Uri uri = Uri.parse(url);

    Intent intent = null;
    // Check to see if someone is trying to play a YouTube page.
    if (url.contains(YOU_TUBE)) {
        // If we don't do it this way you don't have the option for youtube
        uri = Uri.parse("vnd.youtube:" + uri.getQueryParameter("v"));
        if (isYouTubeInstalled()) {
            intent = new Intent(Intent.ACTION_VIEW, uri);
        } else {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=com.google.android.youtube"));
        }
    } else if (url.contains(ASSETS)) {
        // get file path in assets folder
        String filepath = url.replace(ASSETS, "");
        // get actual filename from path as command to write to internal storage doesn't like folders
        String filename = filepath.substring(filepath.lastIndexOf("/") + 1, filepath.length());

        // Don't copy the file if it already exists
        File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + filename);
        if (!fp.exists()) {
            this.copy(filepath, filename);
        }

        // change uri to be to the new file in internal storage
        uri = Uri.parse("file://" + this.cordova.getActivity().getFilesDir() + "/" + filename);

        // Display video player
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "video/*");
    } else {
        // Display video player
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "video/*");
    }

    this.cordova.getActivity().startActivity(intent);
}

From source file:com.phonegap.plugins.videoplayer.VideoPlayer.java

private void playVideo(String url) throws IOException {

    if (url.contains("bit.ly/") || url.contains("goo.gl/") || url.contains("tinyurl.com/")
            || url.contains("youtu.be/")) {
        //support for google / bitly / tinyurl / youtube shortens
        URLConnection con = new URL(url).openConnection();
        con.connect();//from w  w w  .ja va2 s.  c  o m
        InputStream is = con.getInputStream();
        //new redirected url
        url = con.getURL().toString();
        is.close();
    }

    // Create URI
    Uri uri = Uri.parse(url);

    Intent intent = null;
    // Check to see if someone is trying to play a YouTube page.
    if (url.contains(YOU_TUBE)) {
        // If we don't do it this way you don't have the option for youtube
        uri = Uri.parse("vnd.youtube:" + uri.getQueryParameter("v"));
        if (isYouTubeInstalled()) {
            intent = new Intent(Intent.ACTION_VIEW, uri);
        } else {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=com.google.android.youtube"));
        }
    } else if (url.contains(ASSETS)) {
        // get file path in assets folder
        String filepath = url.replace(ASSETS, "");
        // get actual filename from path as command to write to internal storage doesn't like folders
        String filename = filepath.substring(filepath.lastIndexOf("/") + 1, filepath.length());

        // Don't copy the file if it already exists
        File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + filename);
        if (!fp.exists()) {
            this.copy(filepath, filename);
        }

        // change uri to be to the new file in internal storage
        uri = Uri.parse("file://" + this.cordova.getActivity().getFilesDir() + "/" + filename);

        // Display video player
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "video/*");
    } else {
        // Display video player
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "video/*");
    }

    this.cordova.getActivity().startActivity(intent);
}

From source file:com.amaze.filemanager.utils.Futils.java

public void openunknown(File f, Context c, boolean forcechooser) {
    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_VIEW);

    String type = MimeTypes.getMimeType(f);
    if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
        Uri uri = fileToContentUri(c, f);
        if (uri == null)
            uri = Uri.fromFile(f);/*w  w  w  .  j a va 2 s .  com*/
        intent.setDataAndType(uri, type);
        Intent startintent;
        if (forcechooser)
            startintent = Intent.createChooser(intent, c.getResources().getString(R.string.openwith));
        else
            startintent = intent;
        try {
            c.startActivity(startintent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c);
        }
    } else {
        openWith(f, c);
    }

}

From source file:com.mantz_it.rfanalyzer.SettingsFragment.java

@Override
public boolean onPreferenceClick(Preference preference) {
    // FileSource file:
    if (preference.getKey().equals(getString(R.string.pref_filesource_file))) {
        try {//from w  ww .j ava2s. co  m
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(Intent.createChooser(intent, "Select a file (8-bit complex IQ samples)"),
                    FILESOURCE_RESULT_CODE);

            // No error so far... let's dismiss the text input dialog:
            Dialog dialog = ((EditTextPreference) preference).getDialog();
            if (dialog != null)
                dialog.dismiss();
            return true;
        } catch (ActivityNotFoundException e) {
            Toast.makeText(SettingsFragment.this.getActivity(), "No file browser is installed!",
                    Toast.LENGTH_LONG).show();
            // Note that there is still the text dialog visible for the user to input a file path... so no more error handling necessary
        }
        return false;
    }
    // Show Log:
    else if (preference.getKey().equals(getString(R.string.pref_showLog))) {
        try {
            String logfile = ((EditTextPreference) findPreference(getString(R.string.pref_logfile))).getText();
            Uri uri = Uri.fromFile(new File(logfile));
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "text/plain");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            this.startActivity(intent);
            return true;
        } catch (ActivityNotFoundException e) {
            Toast.makeText(SettingsFragment.this.getActivity(), "No text viewer is installed!",
                    Toast.LENGTH_LONG).show();
        }
        return false;
    }
    return false;
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public void launchVideoPlayer(final Activity activity, final String moviePath) {

    try {//  w  ww  .java2  s .co  m
        Intent tostart = new Intent(Intent.ACTION_VIEW);
        tostart.setDataAndType(Uri.parse("file://" + moviePath), "video/*");
        activity.startActivity(tostart);
    } catch (android.content.ActivityNotFoundException e) {
        Log.e(TAG, " Cant start activity to show video!");

        e.printStackTrace();

        new AlertDialog.Builder(activity).setMessage(R.string.cant_show_video)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }
                }).show();

        return;
    }

}

From source file:com.kiva.ohmylinux.MainActivity.java

/**
 * ??/*from  www .  j a  va2 s .c  o  m*/
 *
 * @param profile ???
 */
private void doLaunch(LinuxProfile profile) {
    String command = LaunchUtils.createTerminalCommand(this, profile);
    Intent i = LaunchUtils.createTerminalIntent(profile.getNickName(), command);

    try {
        profile.getOmlInterface().onLaunch(this, profile);
        startActivity(i);
        profile.getOmlInterface().onPostLaunch(this, profile);
    } catch (Exception e) {
        L.e(e);
        new AlertDialog.Builder(this).setTitle(R.string.launch_field).setMessage(R.string.no_terminal_found)
                .setPositiveButton(R.string.install, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        byte[] termBuffer = ResourceUtils.readAssetsFile(MainActivity.this, "terminal");
                        File saveTo = new File(MainActivity.this.getExternalCacheDir(), "term.apk");
                        if (!FileUtils.writeFile(saveTo, termBuffer)) {
                            L.e("cannot extract terminal from apk archive!");
                        }

                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setDataAndType(Uri.fromFile(saveTo), "application/vnd.android.package-archive");
                        startActivity(i);
                    }
                }).setNegativeButton(android.R.string.no, null).show();
    }
}

From source file:ee.ioc.phon.android.speak.RecognizerIntentActivity.java

/**
 * Sets the RESULT_OK intent. Adds the recorded audio data if the caller has requested it
 * and the requested format is supported or unset.
 *///from w  w w  .j  a  va  2 s  . co  m
private void setResultIntent(final Handler handler, ArrayList<String> matches) {
    Intent intent = new Intent();
    if (mExtras.getBoolean(Extras.GET_AUDIO)) {
        String audioFormat = mExtras.getString(Extras.GET_AUDIO_FORMAT);
        if (audioFormat == null) {
            audioFormat = Constants.DEFAULT_AUDIO_FORMAT;
        }
        if (Constants.SUPPORTED_AUDIO_FORMATS.contains(audioFormat)) {
            try {
                FileOutputStream fos = openFileOutput(Constants.AUDIO_FILENAME, Context.MODE_PRIVATE);
                fos.write(mService.getCompleteRecordingAsWav());
                fos.close();

                Uri uri = Uri
                        .parse("content://" + FileContentProvider.AUTHORITY + "/" + Constants.AUDIO_FILENAME);
                // TODO: not sure about the type (or if it's needed)
                intent.setDataAndType(uri, audioFormat);
            } catch (FileNotFoundException e) {
                Log.e(LOG_TAG, "FileNotFoundException: " + e.getMessage());
            } catch (IOException e) {
                Log.e(LOG_TAG, "IOException: " + e.getMessage());
            }
        } else {
            if (Log.DEBUG) {
                handler.sendMessage(createMessage(MSG_TOAST,
                        String.format(getString(R.string.toastRequestedAudioFormatNotSupported), audioFormat)));
            }
        }
    }
    intent.putStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS, matches);
    setResult(Activity.RESULT_OK, intent);
}