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.ximai.savingsmore.save.activity.AddGoodsAcitivyt.java

private void openAlbum() {
    Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
    openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
    startActivityForResult(openAlbumIntent, PICK_FROM_IMAGE);
}

From source file:net.evecom.android.web.Web0Activity.java

public Intent getFileIntent(File file) {
    // Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
    Uri uri = Uri.fromFile(file);/*from   w w w. j  av  a2  s.com*/
    String type = getMIMEType(file);
    Log.i("tag", "type=" + type);
    Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(uri, type);
    return intent;
}

From source file:com.devpaul.filepickerlibrary.FilePickerActivity.java

/**
 * Initializes all the views in the layout of the activity.
 *//*from  w w  w .j  a va 2s  .c  o m*/
private void initializeViews() {
    directoryTitle = (TextView) findViewById(R.id.file_directory_title);
    addButton = (MaterialFloatingActionButton) findViewById(R.id.file_picker_add_button);
    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NameFileDialog nfd = NameFileDialog.newInstance();
            nfd.show(getFragmentManager(), "NameDialog");
        }
    });

    if (fabColorId != -1) {
        addButton.setButtonColor(getResources().getColor(fabColorId));
    }
    selectButton = (Button) findViewById(R.id.select_button);
    selectButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (requestCode == REQUEST_DIRECTORY) {
                if (currentFile.isDirectory()) {
                    curDirectory = currentFile;
                    data = new Intent();
                    data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath());
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    SnackbarManager.show(Snackbar.with(FilePickerActivity.this)
                            .text(R.string.file_picker_snackbar_select_directory_message).duration(1500));
                }
            } else { //request code is for a file
                if (currentFile.isDirectory()) {
                    curDirectory = currentFile;
                    new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory);
                } else {
                    if (mimeType != null) {
                        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
                        String requiredExtension = "." + mimeTypeMap.getExtensionFromMimeType(mimeType);
                        if (requiredExtension.equalsIgnoreCase(fileExt(currentFile.toString()))) {
                            data = new Intent();
                            data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath());
                            setResult(RESULT_OK, data);
                            finish();
                        } else {
                            SnackbarManager.show(Snackbar.with(FilePickerActivity.this)
                                    .text(String.format(
                                            getString(R.string.file_picker_snackbar_select_file_ext_message),
                                            requiredExtension))
                                    .duration(1500));
                        }
                    } else {
                        data = new Intent();
                        data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath());
                        setResult(RESULT_OK, data);
                        finish();
                    }
                }
            }
        }
    });

    openButton = (Button) findViewById(R.id.open_button);
    openButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentFile.isDirectory()) {
                curDirectory = currentFile;
                directoryTitle.setText(curDirectory.getName());

                new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory);
            } else {
                Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);
                String file = currentFile.toString();
                if (file != null) {
                    newIntent.setDataAndType(Uri.fromFile(currentFile), mimeType);
                    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        startActivity(newIntent);
                    } catch (android.content.ActivityNotFoundException e) {
                        SnackbarManager.show(Snackbar.with(FilePickerActivity.this)
                                .text(R.string.file_picker_snackbar_no_file_type_handler));
                    }
                } else {
                    SnackbarManager.show(Snackbar.with(FilePickerActivity.this)
                            .text(R.string.file_picker_snackbar_no_read_type));
                }

            }
        }
    });

    buttonContainer = (LinearLayout) findViewById(R.id.button_container);
    buttonContainer.setVisibility(View.INVISIBLE);

    header = (RelativeLayout) findViewById(R.id.header_container);
}

From source file:com.giovanniterlingen.windesheim.view.DownloadsActivity.java

private void updateFilesList() {
    final File path = Environment.getExternalStoragePublicDirectory(
            ApplicationLoader.applicationContext.getResources().getString(R.string.app_name));
    File files[] = path.listFiles();
    if (files != null && files.length > 0) {
        List<NatschoolContent> contents = new ArrayList<>();
        for (File f : files) {
            if (!f.isDirectory()) {
                contents.add(new NatschoolContent(f.getName()));
            }/*  w ww.  j  av  a 2 s .co m*/
        }
        if (contents.size() == 0) {
            showEmptyTextview();
        } else {
            hideEmptyTextview();
        }
        if (recyclerView == null) {
            recyclerView = findViewById(R.id.downloads_recyclerview);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
        }
        recyclerView.setAdapter(new NatschoolContentAdapter(this, contents) {
            @Override
            protected void onContentClick(NatschoolContent content, int position) {
                Uri uri;
                File file = new File(path.getAbsolutePath() + File.separator + content.name);
                Intent target = new Intent(Intent.ACTION_VIEW);
                if (android.os.Build.VERSION.SDK_INT >= 24) {
                    uri = FileProvider.getUriForFile(DownloadsActivity.this,
                            "com.giovanniterlingen.windesheim.provider", file);
                    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    uri = Uri.fromFile(file);
                    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                }
                String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(uri.toString());
                String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                target.setDataAndType(uri, mimetype);

                try {
                    startActivity(target);
                } catch (ActivityNotFoundException e) {
                    if (view != null) {
                        Snackbar snackbar = Snackbar.make(view, getResources().getString(R.string.no_app_found),
                                Snackbar.LENGTH_SHORT);
                        snackbar.show();
                    }
                }
            }
        });
    } else {
        showEmptyTextview();
    }
}

From source file:com.IntimateCarCare.MainActivity.java

/**
 * ?/*  w w w  .  jav a  2s . c om*/
 */
public void cropRawPhoto(Uri uri) {

    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");

    // ?
    intent.putExtra("crop", "true");

    // aspectX, aspectY:
    intent.putExtra("aspectX", 2);
    intent.putExtra("aspectY", 1);

    // outputX , outputY : ?
    intent.putExtra("outputX", output_X);
    intent.putExtra("outputY", output_Y);
    // intent.putExtra("return-data", true);
    File bitmapFile = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME);
    Uri uritempFile = Uri.fromFile(bitmapFile);
    // Uri uritempFile = Uri.parse("file://" + "/" +
    // Environment.getExternalStorageDirectory().getPath() + "/"
    // +IMAGE_FILE_NAME);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
    // intent.putExtra("outputFormat",
    // Bitmap.CompressFormat.JPEG.toString());
    startActivityForResult(intent, CODE_RESULT_REQUEST);
}

From source file:com.cbtec.eliademy.EliademyLms.java

/**
 * Executes the request.// w  w  w.ja va2 s . co  m
 * 
 * This method is called from the WebView thread. To do a non-trivial amount
 * of work, use: cordova.getThreadPool().execute(runnable);
 * 
 * To run on the UI thread, use:
 * cordova.getActivity().runOnUiThread(runnable);
 * 
 * @param action
 *            The action to execute.
 * @param rawArgs
 *            The exec() arguments in JSON form.
 * @param callbackContext
 *            The callback context used when calling back into JavaScript.
 * @return Whether the action was valid.
 * @throws JSONException
 */
@Override
public boolean execute(String action, JSONArray data, final CallbackContext callbackContext)
        throws JSONException {

    Log.i("HLMS", action);

    if ((action.compareTo("openfilesrv") == 0)) {
        try {
            Uri fileuri = Uri.parse(data.getString(0));
            Intent intent = new Intent(Intent.ACTION_VIEW);
            String mimeextn = android.webkit.MimeTypeMap.getFileExtensionFromUrl(data.getString(0));
            if (mimeextn.isEmpty()) {
                mimeextn = data.getString(0).substring(data.getString(0).indexOf(".") + 1);
                ;
            }
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(mimeextn);
            Log.i("HLMS", fileuri + "  " + mimetype);
            intent.setDataAndType(fileuri, mimetype);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            cordova.getActivity().getApplicationContext().startActivity(intent);
            callbackContext.success();
        } catch (Exception e) {
            Log.e("HLMS", "exception", e);
            callbackContext.error(0);
        }
        return true;
    } else if ((action.compareTo("getfilesrv") == 0)) {
        this.mCallbackContext = callbackContext;
        cordova.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");// TODO: Restrict file types
                    cordova.startActivityForResult(EliademyLms.this, intent, submitFileCode);
                } catch (Exception e) {
                    Log.e("HLMS", "exception", e);
                    callbackContext.error(0);
                }
                return;
            }
        });
    } else if ((action.compareTo("initservice") == 0)) {
        if (!mIsBound) {
            this.mCallbackContext = callbackContext;
            JSONObject tmp = new JSONObject(data.getString(0));
            String sname = tmp.getString("servicename");
            if (sname.contains("eliademy")) {
                mServiceName = "com.cbtec.serviceeliademy";
            } else {
                // From url determine version 2.2, 2.3, 2.4 and change
                mServiceName = "com.cbtec.service" + sname;
            }
            Log.i("HLMS", "Connecting to service: " + mServiceName);
            doBindService();
        } else {
            callbackContext.success();
        }
        return true;
    } else {
        final String aAction = action;
        final JSONArray aData = data;
        String mappedCmd = null;
        try {
            mappedCmd = mapExecCommand(aData.getString(0));
        } catch (JSONException e) {
            Log.e("HLMS", "exception", e);
        }
        if (mappedCmd == null) {
            Log.i("HLMS", "LMS service call failed " + mappedCmd);
            callbackContext.error(0);// TODO : error enum
            return false;
        }

        final String execCmd = mappedCmd;
        cordova.getThreadPool().execute(new Runnable() {
            @Override
            @SuppressLint("NewApi")
            public void run() {
                Log.i("HLMS", "Runner execute " + aAction + aData.toString());
                if (aAction.compareTo("lmsservice") == 0) {
                    try {
                        String retval = null;
                        Log.i("HLMS", "Execute cmd: " + execCmd);
                        if (execCmd.compareTo("initialize") == 0) {
                            if (mIBinder.initializeService(aData.getString(1))) {
                                String token = mIBinder.eliademyGetWebServiceToken();
                                callbackContext.success(token);
                                return;
                            }
                        } else if (execCmd.compareTo("deinitialize") == 0) {
                            if (mIBinder.deInitializeService(aData.getString(1))) {
                                doUnbindService();
                                callbackContext.success();
                                return;
                            }
                        } else if (execCmd.compareTo("pushregister") == 0) {
                            Log.i("pushdata", aData.getString(1));
                            if (mIBinder.registerPushNotifications(aData.getString(1))) {
                                callbackContext.success();
                                return;
                            }
                        } else if (execCmd.compareTo("pushunregister") == 0) {
                            Log.i("pushdata", aData.getString(1));
                            if (mIBinder.unregisterPushNotifications(aData.getString(1))) {
                                callbackContext.success();
                                return;
                            }
                        } else if (execCmd.compareTo("servicetoken") == 0) {
                            retval = mIBinder.eliademyGetWebServiceToken();
                        } else if (execCmd.compareTo("siteinfo") == 0) {
                            retval = mIBinder.eliademyGetSiteInformation(aData.getString(1));
                        } else if (execCmd.compareTo("get_user_courses") == 0) {
                            retval = mIBinder.eliademyGetUsersCourses(aData.getString(1));
                        } else if (execCmd.compareTo("get_user_forums") == 0) {
                            retval = mIBinder.eliademyGetUserForums(aData.getString(1));
                        } else if (execCmd.compareTo("get_user_info") == 0) {
                            retval = mIBinder.eliademyGetUserInformation(aData.getString(1));
                        } else if (execCmd.compareTo("exec_webservice") == 0) {
                            Log.i("HLMS", "Execute webservice");
                            retval = mIBinder.eliademyExecWebService(aData.getString(0), aData.getString(1));
                        } else if (execCmd.compareTo("course_get_contents") == 0) {
                            retval = mIBinder.eliademyGetCourseContents(aData.getString(1));
                        } else if (execCmd.compareTo("course_get_enrolled_users") == 0) {
                            retval = mIBinder.eliademyGetEnrolledUsers(aData.getString(1));
                        } else {
                            Log.i("HLMS", "LMS service failed " + execCmd);
                            callbackContext.error(0);// TODO : error enum
                        }
                        if (!retval.isEmpty()) {
                            Log.i("HLMS", "LMS service call success");
                            callbackContext.success(retval);
                        } else {
                            Log.i("HLMS", "LMS service call failed");
                            callbackContext.error(0);// TODO : error enum
                        }
                    } catch (Exception e) {
                        Log.e("HLMS", "exception", e);
                        callbackContext.error(e.getMessage());
                        return;
                    }
                } else {
                    Log.i("LMS", "Unsupported action call !!");
                    callbackContext.error(0);
                    return;
                }
            }
        });
    }
    return true;
}

From source file:com.ccxt.whl.activity.SettingsFragmentCopy.java

/**
 * ?// w  w  w .j  av a  2s .  c  om
 * @param uri
 * @param outputX
 * @param outputY
 * @param requestCode
 */
private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
    /*if(getpathfromUri(uri)!=null&&getpathfromUri(imageUri)!=null){
     copyFile(getpathfromUri(uri),getpathfromUri(imageUri));
    }else{
       return;
    }*/
    Log.d("log", uri.toString());
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    //aspectX aspectY
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    // outputX outputY ?
    intent.putExtra("outputX", outputX);
    intent.putExtra("outputY", outputY);
    intent.putExtra("scale", true);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    intent.putExtra("return-data", false);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    intent.putExtra("noFaceDetection", true); // no face detection
    startActivityForResult(intent, requestCode);
}

From source file:android.support.v7.media.RemotePlaybackClient.java

private void playOrEnqueue(Uri contentUri, String mimeType, Bundle metadata, long positionMillis, Bundle extras,
        final ItemActionCallback callback, String action) {
    if (contentUri == null) {
        throw new IllegalArgumentException("contentUri must not be null");
    }/*from  ww  w.j a va2  s  .c  o m*/
    throwIfRemotePlaybackNotSupported();
    if (action.equals(MediaControlIntent.ACTION_ENQUEUE)) {
        throwIfQueuingNotSupported();
    }

    Intent intent = new Intent(action);
    intent.setDataAndType(contentUri, mimeType);
    intent.putExtra(MediaControlIntent.EXTRA_ITEM_STATUS_UPDATE_RECEIVER, mItemStatusPendingIntent);
    if (metadata != null) {
        intent.putExtra(MediaControlIntent.EXTRA_ITEM_METADATA, metadata);
    }
    if (positionMillis != 0) {
        intent.putExtra(MediaControlIntent.EXTRA_ITEM_CONTENT_POSITION, positionMillis);
    }
    performItemAction(intent, mSessionId, null, extras, callback);
}

From source file:com.android.music.MusicBrowserActivity.java

/**
 * get current view/*from www . j  a  va 2  s  . c  om*/
 *
 * @param index
 * @return View
 */
private View getView(int index) {
    MusicLogUtils.d(TAG, "getView>>>index = " + index);
    View view = null;
    Intent intent = new Intent(Intent.ACTION_PICK);
    switch (index) {
    case ARTIST_INDEX:
        intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/artistalbum");
        break;
    case ALBUM_INDEX:
        intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/album");
        break;
    case SONG_INDEX:
        intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
        break;
    case PLAYLIST_INDEX:
        intent.setDataAndType(Uri.EMPTY, MediaStore.Audio.Playlists.CONTENT_TYPE);
        break;
    default:
        MusicLogUtils.d(TAG, "default");
        return null;
    }
    intent.putExtra("withtabs", true);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    view = mActivityManager.startActivity(getStringId(index), intent).getDecorView();
    MusicLogUtils.d(TAG, "getView<<<");
    return view;
}

From source file:eu.alefzero.owncloud.ui.fragment.FileDetailFragment.java

/**
 * Updates the view with all relevant details about that file.
 *///from w  ww . j av  a2  s .c o m
public void updateFileDetails() {

    if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {

        Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
        // set file details
        setFilename(mFile.getFileName());
        setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile.getMimetype()));
        setFilesize(mFile.getFileLength());
        if (ocVersionSupportsTimeCreated()) {
            setTimeCreated(mFile.getCreationTimestamp());
        }

        setTimeModified(mFile.getModificationTimestamp());

        CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
        cb.setChecked(mFile.keepInSync());

        if (mFile.getStoragePath() != null) {
            // Update preview
            if (mFile.getMimetype().startsWith("image/")) {
                BitmapLoader bl = new BitmapLoader();
                bl.execute(new String[] { mFile.getStoragePath() });
            }

            // Change download button to open button
            downloadButton.setText(R.string.filedetails_open);
            downloadButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    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())) {
                                i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mimeType);
                                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();
                            }
                        }

                    }
                }
            });
        } else {
            // Make download button effective
            downloadButton.setOnClickListener(this);
        }
    }
}