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.moust.cordova.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  .  jav 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, "");
        //Remove the path to the file from any location
        if (filepath.contains("www/file:")) {
            filepath = filepath.replace("www/file://", "");
        }
        // 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);

        //It uses a fixed name to optimize memory space
        File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + VIDEO_FILE_NAME);

        //Always copy the file
        //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.jp.miaulavirtual.DisplayMessageActivity.java

public int downloadFile(String request) {
    URL url2;//from   ww w. j a  va2s  .  co  m
    URLConnection conn;
    int lastSlash;
    Long fileSize = null;
    BufferedInputStream inStream;
    BufferedOutputStream outStream;
    FileOutputStream fileStream;
    String cookies = cookieFormat(scookie); // format cookie for URL setRequestProperty
    final int BUFFER_SIZE = 23 * 1024;
    int id = 1;

    File file = null;

    Log.d("Document", "2 respueesta");
    try {
        // Just resources
        lastSlash = url.toString().lastIndexOf('/');

        // Directory creation
        String root = Environment.getExternalStorageDirectory().toString();
        Boolean isSDPresent = android.os.Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);
        // check if is there external storage
        if (!isSDPresent) {
            task_status = false;
            id = 9;
        } else {
            String folder;
            if (comunidades) {
                folder = onData.get(2)[1];
            } else {
                folder = onData.get(1)[1];
            }
            folder = folder.replaceAll(
                    "\\d{4}-\\d{4}\\s|\\d{4}-\\d{2}\\s|Documentos\\sde\\s?|Gr\\..+?\\s|\\(.+?\\)", "");
            folder = folder.toString().trim();
            Log.d("Folder", folder);
            File myDir = new File(root + "/Android/data/com.jp.miaulavirtual/files/" + folder);
            myDir.mkdirs();

            // Document creation
            String name = url.toString().substring(lastSlash + 1);
            file = new File(myDir, name);
            Log.d("Document", name);
            fileSize = (long) file.length();

            // Check if we have already downloaded the whole file
            if (file.exists()) {
                dialog.setProgress(100); // full progress if file already donwloaded
            } else {
                // Start the connection with COOKIES (we already verified that the cookies aren't expired and we can use them)
                url2 = new URL(request);
                conn = url2.openConnection();
                conn.setUseCaches(false);
                conn.setRequestProperty("Cookie", cookies);
                conn.setConnectTimeout(10 * 1000);
                conn.setReadTimeout(20 * 1000);
                fileSize = (long) conn.getContentLength();

                // Check if we have necesary space
                if (fileSize >= myDir.getUsableSpace()) {
                    task_status = false;
                    id = 2;
                } else {

                    // Start downloading
                    inStream = new BufferedInputStream(conn.getInputStream());
                    fileStream = new FileOutputStream(file);
                    outStream = new BufferedOutputStream(fileStream, BUFFER_SIZE);
                    byte[] data = new byte[BUFFER_SIZE];
                    int bytesRead = 0;
                    int setMax = (conn.getContentLength() / 1024);
                    dialog.setMax(setMax);

                    while (task_status && (bytesRead = inStream.read(data, 0, data.length)) >= 0) {
                        outStream.write(data, 0, bytesRead);
                        // update progress bar
                        dialog.incrementProgressBy((int) (bytesRead / 1024));
                    }

                    // Close stream
                    outStream.close();
                    fileStream.close();
                    inStream.close();

                    // Delete file if Cancel button
                    if (!task_status) {
                        file.delete();
                        if (myDir.listFiles().length <= 0)
                            myDir.delete();
                        id = 0;
                    }
                }
            }
            Log.d("Status", String.valueOf(task_status));
            // Open file
            if (task_status) {
                Log.d("Type", "Hola2");
                dialog.dismiss();
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);

                MimeTypeMap mime = MimeTypeMap.getSingleton();
                // Get extension file
                String file_s = file.toString();
                String extension = "";

                int i = file_s.lastIndexOf('.');
                int p = Math.max(file_s.lastIndexOf('/'), file_s.lastIndexOf('\\'));

                if (i > p) {
                    extension = file_s.substring(i + 1);
                }

                // Get extension reference
                String doc_type = mime.getMimeTypeFromExtension(extension);

                Log.d("Type", extension);

                intent.setDataAndType(Uri.fromFile(file), doc_type);
                startActivity(intent);
            }
        }
    } catch (MalformedURLException e) // Invalid URL
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 3;
    } catch (FileNotFoundException e) // FIle not found
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 4;
    } catch (SocketTimeoutException e) // time out
    {
        Log.d("Timeout", "Timeout");
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 7;
    } catch (Exception e) // General error
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 8;
    }
    Log.d("Type", String.valueOf(id));
    Log.d("StartOk3", "Como he llegado hasta aqu?");
    // notify completion
    Log.d("ID", String.valueOf(id));
    return id;

}

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

/**
 * Returns the intent with uri corresponding to specific {@link HybridFileParcelable} back to external app
 *///  w w  w  . j a  v a  2 s.c  o  m
public void returnIntentResults(HybridFileParcelable baseFile) {

    getMainActivity().mReturnIntent = false;

    Intent intent = new Intent();
    if (getMainActivity().mRingtonePickerIntent) {

        Uri mediaStoreUri = MediaStoreHack.getUriFromFile(baseFile.getPath(), getActivity());
        Log.d(getClass().getSimpleName(), mediaStoreUri.toString() + "\t"
                + MimeTypes.getMimeType(baseFile.getPath(), baseFile.isDirectory()));
        intent.setDataAndType(mediaStoreUri, MimeTypes.getMimeType(baseFile.getPath(), baseFile.isDirectory()));
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, mediaStoreUri);
        getActivity().setResult(FragmentActivity.RESULT_OK, intent);
        getActivity().finish();
    } else {

        Log.d("pickup", "file");

        Intent intentresult = new Intent();

        Uri resultUri = Utils.getUriForBaseFile(getActivity(), baseFile);
        intentresult.setAction(Intent.ACTION_SEND);
        intentresult.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        if (resultUri != null)
            intentresult.setDataAndType(resultUri, MimeTypes.getExtension(baseFile.getPath()));

        getActivity().setResult(FragmentActivity.RESULT_OK, intentresult);
        getActivity().finish();
        //mode.finish();
    }
}

From source file:com.amaze.carbonfilemanager.fragments.MainFragment.java

private void returnIntentResults(File file) {
    MAIN_ACTIVITY.mReturnIntent = false;

    Intent intent = new Intent();
    if (MAIN_ACTIVITY.mRingtonePickerIntent) {

        Uri mediaStoreUri = MediaStoreHack.getUriFromFile(file.getPath(), getActivity());
        System.out.println(mediaStoreUri.toString() + "\t" + MimeTypes.getMimeType(file));
        intent.setDataAndType(mediaStoreUri, MimeTypes.getMimeType(file));
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, mediaStoreUri);
        getActivity().setResult(FragmentActivity.RESULT_OK, intent);
        getActivity().finish();//from  w  ww  .ja va 2s  . com
    } else {

        Log.d("pickup", "file");
        intent.setData(Uri.fromFile(file));
        getActivity().setResult(FragmentActivity.RESULT_OK, intent);
        getActivity().finish();
    }
}

From source file:com.oakesville.mythling.MediaActivity.java

protected void playLiveStream(LiveStreamInfo streamInfo, Item item) throws IOException, JSONException {
    String streamUrl = appSettings.getMythTvServicesBaseUrlWithCredentials() + streamInfo.getRelativeUrl();

    // avoid retrieving unnecessary audio-only streams
    int lastDot = streamUrl.lastIndexOf('.');
    streamUrl = streamUrl.substring(0, lastDot) + ".av" + streamUrl.substring(lastDot);

    stopProgress();/*from  w ww  . j  a v  a2  s  .co m*/

    PlaybackOption playbackOption = getPlaybackOption(item, PlaybackOptions.STREAM_HLS);
    boolean isExternalPlayer = playbackOption.isAppPlayer();
    if (!isExternalPlayer && item.isRecording() && isUseCutList()) {
        new PlayWithCutListTask(Uri.parse(streamUrl), (Recording) item, playbackOption).execute();
    } else {
        Intent videoIntent = new Intent(Intent.ACTION_VIEW);
        videoIntent.setDataAndType(Uri.parse(streamUrl), "video/*");
        if (!playbackOption.isAppPlayer()) {
            videoIntent.setClass(getApplicationContext(), VideoPlayerActivity.class);
            videoIntent.putExtra(VideoPlayerActivity.PLAYER, playbackOption.getPlayer());
            if (item.isLengthKnown())
                videoIntent.putExtra(VideoPlayerActivity.ITEM_LENGTH_SECS, item.getLength());
        }
        startActivity(videoIntent);
    }
}

From source file:com.oakesville.mythling.MediaActivity.java

/**
 * Requires MythTV content.cpp patch to work without storage groups.
 *///from  w w  w  .  ja v a2  s  .c  om
private void playRawVideoStream(Item item) throws IOException, JSONException {

    Uri uri;
    if (item.isDownloaded()) {
        uri = getDownload(item);
    } else {
        URL baseUrl = getAppSettings().getMythTvServicesBaseUrlWithCredentials();
        String fileUrl = baseUrl + "/Content/GetFile?";
        if (item.getStorageGroup() == null)
            fileUrl += "StorageGroup=None&";
        else
            fileUrl += "StorageGroup=" + item.getStorageGroup().getName() + "&";
        fileUrl += "FileName=" + URLEncoder.encode(item.getFilePath(), "UTF-8");

        uri = Uri.parse(fileUrl);
    }

    PlaybackOption playbackOption = getPlaybackOption(item, PlaybackOptions.STREAM_FILE);
    boolean isExternalPlayer = playbackOption.isAppPlayer();
    if (!isExternalPlayer && item.isRecording() && isUseCutList()) {
        new PlayWithCutListTask(uri, (Recording) item, playbackOption).execute();
    } else {
        stopProgress();
        Intent videoIntent = new Intent(Intent.ACTION_VIEW);
        videoIntent.setDataAndType(uri, "video/*");
        if (!isExternalPlayer) {
            videoIntent.setClass(getApplicationContext(), VideoPlayerActivity.class);
            videoIntent.putExtra(VideoPlayerActivity.PLAYER, playbackOption.getPlayer());
            if (!item.isDownloaded()) {
                if (item.isLengthKnown())
                    videoIntent.putExtra(VideoPlayerActivity.ITEM_LENGTH_SECS, item.getLength());
                String streamingAuthType = getAppSettings().getMythTvServicesAuthType();
                if (streamingAuthType != AuthType.None.toString())
                    videoIntent.putExtra(VideoPlayerActivity.AUTH_TYPE, streamingAuthType);
            }
        }
        startActivity(videoIntent);
    }
}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * ??.//from  w  w w. j  a v a 2  s .  c om
 * 
 * @return ID
 */
public int playMedia() {
    if (mSetMediaType == MEDIA_TYPE_MUSIC) {
        try {
            mMediaPlayer.prepare();
            if (mMediaStatus == MEDIA_PLAYER_STOP) {
                mMediaPlayer.seekTo(0);
            }
            mMediaPlayer.start();
            mMediaStatus = MEDIA_PLAYER_PLAY;
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                e.printStackTrace();
            }
        }
        sendOnStatusChangeEvent("play");
        return mMediaPlayer.getAudioSessionId();
    } else if (mSetMediaType == MEDIA_TYPE_VIDEO) {
        String className = getClassnameOfTopActivity();

        if (VideoPlayer.class.getName().equals(className)) {
            mMediaStatus = MEDIA_PLAYER_PLAY;
            Intent mIntent = new Intent(VideoConst.SEND_HOSTDP_TO_VIDEOPLAYER);
            mIntent.putExtra(VideoConst.EXTRA_NAME, VideoConst.EXTRA_VALUE_VIDEO_PLAYER_PLAY);
            this.getContext().sendBroadcast(mIntent);
            sendOnStatusChangeEvent("play");

        } else {
            mMediaStatus = MEDIA_PLAYER_PLAY;
            Intent mIntent = new Intent(VideoConst.SEND_HOSTDP_TO_VIDEOPLAYER);
            mIntent.setClass(getContext(), VideoPlayer.class);
            Uri data = Uri.parse(myCurrentFilePath);
            mIntent.setDataAndType(data, myCurrentFileMIMEType);
            mIntent.putExtra(VideoConst.EXTRA_NAME, VideoConst.EXTRA_VALUE_VIDEO_PLAYER_PLAY);
            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(mIntent);
            sendOnStatusChangeEvent("play");

        }

        return 0;
    } else {
        return 0;
    }
}

From source file:org.thoughtland.xlocation.ActivityShare.java

public void fileChooser() {
    Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/.xlocation/");
    chooseFile.setDataAndType(uri, "text/xml");
    Intent intent = Intent.createChooser(chooseFile, getString(R.string.app_name));
    startActivityForResult(intent, ACTIVITY_IMPORT_SELECT);
}

From source file:biz.bokhorst.xprivacy.ActivityShare.java

public void fileChooser() {
    Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/.xprivacy/");
    chooseFile.setDataAndType(uri, "text/xml");
    Intent intent = Intent.createChooser(chooseFile, getString(R.string.app_name));
    startActivityForResult(intent, ACTIVITY_IMPORT_SELECT);
}