Example usage for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION

List of usage examples for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION

Introduction

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

Prototype

int FLAG_GRANT_WRITE_URI_PERMISSION

To view the source code for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION.

Click Source Link

Document

If set, the recipient of this Intent will be granted permission to perform write operations on the URI in the Intent's data and any URIs specified in its ClipData.

Usage

From source file:com.HumanDecisionSupportSystemsLaboratory.DD_P2P.SafeProfileFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (peer.getSK() == null) {
        return;/*from  w  w  w  .  j  a  va2  s  .  c om*/
    }
    if (resultCode == Activity.RESULT_OK && resultData != null) {
        Uri uri = null;

        if (requestCode == SELECT_PROFILE_PHOTO) {
            uri = resultData.getData();
            Log.i("Uri", "Uri: " + uri.toString());
        } else if (requestCode == SELECT_PPROFILE_PHOTO_KITKAT) {
            uri = resultData.getData();
            Log.i("Uri_kitkat", "Uri: " + uri.toString());
            final int takeFlags = resultData.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getActivity().getContentResolver().takePersistableUriPermission(uri, takeFlags);
        }

        selectedImagePath = FileUtils.getPath(getActivity(), uri);
        Log.i("path", "path: " + selectedImagePath);

        selectImageFile = new File(selectedImagePath);

        /*         Bitmap bmp = BitmapFactory.decodeFile(selectedImagePath);*/
        // String strFromBmp = PhotoUtil.BitmapToString(bmp);

        Bitmap bmp = PhotoUtil.decodeSampledBitmapFromFile(selectedImagePath, 80, 80);
        //TODO fix the loading image
        byte[] icon;
        icon = PhotoUtil.BitmapToByteArray(bmp, 100);
        /*      int quality = 100;*/
        Log.i(TAG, "SafeProfile: Icon length=" + icon.length);
        /*DD.MAX_PEER_ICON_LENGTH = 30000;
        while (icon.length > DD.MAX_PEER_ICON_LENGTH && quality > 0) {
           quality -= 5;
           icon = PhotoUtil.BitmapToByteArray(bmp, quality);
           Log.i(TAG, "SafeProfile: Icon length=" + icon.length
          + " quality=" + quality);
        }
        Log.i(TAG, "SafeProfile: Icon length=" + icon.length + " quality="
              + quality);// Util.stringSignatureFromByte(icon));
        */ if (peer != null) {
            peer = D_Peer.getPeerByPeer_Keep(peer);
        }
        if (peer != null) {
            if (peer.getSK() != null) {
                if (peer.setIcon(icon)) {
                    peer.sign();
                    peer.storeRequest();
                }
                peer.releaseReference();
            }
        }

        imgbut.setImageBitmap(bmp);

    }
}

From source file:org.telegram.ui.Components.ImageUpdater.java

public void openCamera() {
    if (parentFragment == null || parentFragment.getParentActivity() == null) {
        return;/*w  w  w .  j  a v  a 2  s .  c o m*/
    }
    try {
        if (Build.VERSION.SDK_INT >= 23 && parentFragment.getParentActivity()
                .checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            parentFragment.getParentActivity().requestPermissions(new String[] { Manifest.permission.CAMERA },
                    19);
            return;
        }
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File image = AndroidUtilities.generatePicturePath();
        if (image != null) {
            if (Build.VERSION.SDK_INT >= 24) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(
                        parentFragment.getParentActivity(), BuildConfig.APPLICATION_ID + ".provider", image));
                takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
            }
            currentPicturePath = image.getAbsolutePath();
        }
        parentFragment.startActivityForResult(takePictureIntent, 13);
    } catch (Exception e) {
        FileLog.e(e);
    }
}

From source file:de.k3b.android.toGoZip.SettingsActivity.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static void grandPermission5(Context ctx, Uri data) {
    DocumentFile docPath = DocumentFile.fromTreeUri(ctx, data);
    if (docPath != null) {
        final ContentResolver resolver = ctx.getContentResolver();
        resolver.takePersistableUriPermission(data,
                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    }/*from www .ja v  a 2  s.  com*/
}

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

/**
 * Updates the view with all relevant details about that file.
 *//* ww  w  .ja v  a2  s .  co  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);
        }
    }
}

From source file:org.mklab.mikity.android.MainActivity.java

/**
 * This is called after the file manager finished. {@inheritDoc}
 *///ww  w. j a  va2 s.c o  m
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    super.onActivityResult(requestCode, resultCode, resultData);

    switch (requestCode) {
    case REQUEST_CODE_LOAD_MODEL_DATA_FILE:
        if (resultCode == RESULT_OK && resultData != null) {
            final Uri uri = resultData.getData();

            final int takeFlags = resultData.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            getContentResolver().takePersistableUriPermission(uri, takeFlags);

            loadModelData(uri);
        }
        break;
    case REQUEST_CODE_LOAD_SOURCE_DATA_FILE:
        if (resultCode == RESULT_OK && resultData != null) {
            final Uri uri = resultData.getData();
            loadSourceData(uri, this.sourceIdForIntent);
        }
        break;
    case REQUEST_CODE_SAVE_MODEL_DATA_FILE:
        if (resultCode == RESULT_OK && resultData != null) {
            final Uri uri = resultData.getData();
            saveAsModelData(uri);
        }
        break;
    default:
        break;
    }
}

From source file:com.keepassdroid.fileselect.FileSelectActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    fillData();/*from  w w w  .  j  a  v a 2s  . c om*/

    String filename = null;
    if (requestCode == FILE_BROWSE && resultCode == RESULT_OK) {
        filename = data.getDataString();
        if (filename != null) {
            if (filename.startsWith("file://")) {
                filename = filename.substring(7);
            }

            filename = URLDecoder.decode(filename);
        }

    } else if ((requestCode == GET_CONTENT || requestCode == OPEN_DOC) && resultCode == RESULT_OK) {
        if (data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                if (StorageAF.useStorageFramework(this)) {
                    try {
                        // try to persist read and write permissions
                        ContentResolver resolver = getContentResolver();
                        ContentResolverCompat.takePersistableUriPermission(resolver, uri,
                                Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        ContentResolverCompat.takePersistableUriPermission(resolver, uri,
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    } catch (Exception e) {
                        // nop
                    }
                }
                if (requestCode == GET_CONTENT) {
                    uri = UriUtil.translate(this, uri);
                }
                filename = uri.toString();
            }
        }
    }

    if (filename != null) {
        EditText fn = (EditText) findViewById(R.id.file_filename);
        fn.setText(filename);
    }
}

From source file:com.apptentive.android.sdk.module.engagement.interaction.fragment.MessageCenterFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case Constants.REQUEST_CODE_CLOSE_COMPOSING_CONFIRMATION: {
            onCancelComposing();/*from   ww  w  . jav a 2  s .  co  m*/
            break;
        }
        case Constants.REQUEST_CODE_PHOTO_FROM_SYSTEM_PICKER: {
            if (data == null) {
                ApptentiveLog.d("no image is picked");
                return;
            }
            imagePickerStillOpen = false;
            Uri uri;
            Activity hostingActivity = hostingActivityRef.get();
            //Android SDK less than 19
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                uri = data.getData();
            } else {
                //for Android 4.4
                uri = data.getData();
                int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
                if (hostingActivity != null) {
                    hostingActivity.getContentResolver().takePersistableUriPermission(uri, takeFlags);
                }
            }

            EngagementModule.engageInternal(getActivity(), interaction,
                    MessageCenterInteraction.EVENT_NAME_ATTACH);

            String originalPath = Util.getRealFilePathFromUri(hostingActivity, uri);
            if (originalPath != null) {
                /* If able to retrieve file path and creation time from uri, cache file name will be generated
                 * from the md5 of file path + creation time
                 */
                long creation_time = Util.getContentCreationTime(hostingActivity, uri);
                Uri fileUri = Uri.fromFile(new File(originalPath));
                File cacheDir = Util.getDiskCacheDir(hostingActivity);
                addAttachmentsToComposer(new ImageItem(originalPath,
                        Util.generateCacheFileFullPath(fileUri, cacheDir, creation_time),
                        Util.getMimeTypeFromUri(hostingActivity, uri), creation_time));
            } else {
                /* If not able to get image file path due to not having READ_EXTERNAL_STORAGE permission,
                 * cache name will be generated from md5 of uri string
                 */
                File cacheDir = Util.getDiskCacheDir(hostingActivity);
                String cachedFileName = Util.generateCacheFileFullPath(uri, cacheDir, 0);
                addAttachmentsToComposer(new ImageItem(uri.toString(), cachedFileName,
                        Util.getMimeTypeFromUri(hostingActivity, uri), 0));
            }

            break;
        }
        default:
            break;
        }
    }
}

From source file:be.ppareit.swiftp.gui.PreferenceFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (requestCode == ACTION_OPEN_DOCUMENT_TREE && resultCode == Activity.RESULT_OK) {
        Uri treeUri = resultData.getData();
        String path = treeUri.getPath();

        final CheckBoxPreference writeExternalStorage_pref = findPref("writeExternalStorage");
        if (!":".equals(path.substring(path.length() - 1)) || path.contains("primary")) {
            writeExternalStorage_pref.setChecked(false);
        } else {//from w w w  .  jav a  2  s .  c o m
            FsSettings.setExternalStorageUri(treeUri.toString());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getActivity().getContentResolver().takePersistableUriPermission(treeUri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            writeExternalStorage_pref.setChecked(true);
        }
    }

}

From source file:org.fs.galleon.presenters.ToolsFragmentPresenter.java

private void dispatchTakePictureIntent() {
    createIfNotExists().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(file -> {//from  w ww  .java  2 s. c  om
                if (file.exists()) {
                    log(Log.INFO, String.format(Locale.ENGLISH, "%s is temp file.", file.getAbsolutePath()));
                }
                if (view.isAvailable()) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (intent.resolveActivity(view.getContext().getPackageManager()) != null) {
                        this.tempTakenPhoto = file;//set it in property
                        Uri uri = FileProvider.getUriForFile(view.getContext(), GRANT_PERMISSION, file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        //fileProvider requires gran permission to others access that uri
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                            final Context context = view.getContext();
                            List<ResolveInfo> infos = context.getPackageManager().queryIntentActivities(intent,
                                    PackageManager.MATCH_DEFAULT_ONLY);
                            if (infos != null) {
                                StreamSupport.stream(infos).filter(x -> x.activityInfo != null)
                                        .map(x -> x.activityInfo.packageName).forEach(pack -> {
                                            context.grantUriPermission(pack, uri,
                                                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                                                            | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                        });
                            }
                        }
                        view.startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                    } else {
                        view.showError("You need to install app that can capture photo.");
                    }
                }
            }, this::log);
}

From source file:com.owncloud.android.ui.fragment.FileDetailFragment.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.fdDownloadBtn: {
        FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
        FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
        if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
            downloaderBinder.cancel(mAccount, mFile);
            if (mFile.isDown()) {
                setButtonsForDown();//from w  ww. j  a  v  a 2s  . c  o  m
            } else {
                setButtonsForRemote();
            }

        } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
            uploaderBinder.cancel(mAccount, mFile);
            if (!mFile.fileExists()) {
                // TODO make something better
                if (getActivity() instanceof FileDisplayActivity) {
                    // double pane
                    FragmentTransaction transaction = getActivity().getSupportFragmentManager()
                            .beginTransaction();
                    transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FTAG); // empty FileDetailFragment
                    transaction.commit();
                    mContainerActivity.onFileStateChanged();
                } else {
                    getActivity().finish();
                }

            } else if (mFile.isDown()) {
                setButtonsForDown();
            } else {
                setButtonsForRemote();
            }

        } else {
            mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true,
                    false, getActivity());
            WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount,
                    getSherlockActivity().getApplicationContext());
            mLastRemoteOperation.execute(wc, this, mHandler);

            // update ui 
            boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
            getActivity().showDialog((inDisplayActivity) ? FileDisplayActivity.DIALOG_SHORT_WAIT
                    : FileDetailActivity.DIALOG_SHORT_WAIT);
            setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference

        }
        break;
    }
    case R.id.fdKeepInSync: {
        CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
        mFile.setKeepInSync(cb.isChecked());
        mStorageManager.saveFile(mFile);

        /// register the OCFile instance in the observer service to monitor local updates;
        /// if necessary, the file is download 
        Intent intent = new Intent(getActivity().getApplicationContext(), FileObserverService.class);
        intent.putExtra(FileObserverService.KEY_FILE_CMD,
                (cb.isChecked() ? FileObserverService.CMD_ADD_OBSERVED_FILE
                        : FileObserverService.CMD_DEL_OBSERVED_FILE));
        intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
        intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
        Log.e(TAG, "starting observer service");
        getActivity().startService(intent);

        if (mFile.keepInSync()) {
            onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
        }
        break;
    }
    case R.id.fdRenameBtn: {
        EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title),
                mFile.getFileName(), this);
        dialog.show(getFragmentManager(), "nameeditdialog");
        break;
    }
    case R.id.fdRemoveBtn: {
        ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
                R.string.confirmation_remove_alert, new String[] { mFile.getFileName() },
                mFile.isDown() ? R.string.confirmation_remove_remote_and_local
                        : R.string.confirmation_remove_remote,
                mFile.isDown() ? R.string.confirmation_remove_local : -1, R.string.common_cancel);
        confDialog.setOnConfirmationListener(this);
        mCurrentDialog = confDialog;
        mCurrentDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
        break;
    }
    case R.id.fdOpenBtn: {
        String storagePath = mFile.getStoragePath();
        String encodedStoragePath = WebdavUtils.encodePath(storagePath);
        try {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mFile.getMimetype());
            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            startActivity(i);

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

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

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

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

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

        }
        break;
    }
    default:
        Log.e(TAG, "Incorrect view clicked!");
    }

    /* else if (v.getId() == R.id.fdShareBtn) {
    Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
    t.start();
    }*/
}