Example usage for android.content Intent FLAG_GRANT_READ_URI_PERMISSION

List of usage examples for android.content Intent FLAG_GRANT_READ_URI_PERMISSION

Introduction

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

Prototype

int FLAG_GRANT_READ_URI_PERMISSION

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

Click Source Link

Document

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

Usage

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

@SuppressLint("NewApi")
@Override/*  ww  w . j ava2 s. c o m*/
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (resultCode == 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.
            getContentResolver().takePersistableUriPermission(uri, takeFlags);
        }

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

        Bitmap bmp = BitmapFactory.decodeFile(selectedImagePath);
        // String strFromBmp = PhotoUtil.BitmapToString(bmp);
        byte[] icon = PhotoUtil.BitmapToByteArray(bmp, 100);
        Log.i(TAG, Util.stringSignatureFromByte(icon));

        byteIcon = icon;
        Log.d(TAG, "selected constituent pic: " + byteIcon.length);
        setProfilePhoto.setImageBitmap(bmp);

    }
}

From source file:org.rm3l.maoni.ui.MaoniActivity.java

private void validateAndSubmitForm() {
    //Validate form
    if (this.validateForm(mRootView)) {
        //TODO Check that device is actually connected to the internet prior to going any further
        boolean includeScreenshot = false;
        if (mScreenCapturingFeatureEnabled && mIncludeScreenshot != null) {
            includeScreenshot = mIncludeScreenshot.isChecked();
        }/*from w  w  w . j a  v a  2  s. com*/
        String contentText = "";
        if (mContent != null) {
            contentText = mContent.getText().toString();
        }

        final Intent intent = getIntent();

        Uri screenshotUri = null;
        File screenshotFile = null;
        Uri logsUri = null;
        File logsFile = null;

        final boolean includeLogs = mLogsCapturingFeatureEnabled && mIncludeLogs != null
                && mIncludeLogs.isChecked();
        if (includeLogs) {
            logsFile = new File(mWorkingDir, MAONI_LOGS_FILENAME);
            LogcatUtils.getLogsToFile(logsFile);
        }

        if (intent.hasExtra(FILE_PROVIDER_AUTHORITY)) {
            final String fileProviderAuthority = intent.getStringExtra(FILE_PROVIDER_AUTHORITY);
            //#11 : Potential NPE in Android's FileProvider if Provider Authority couldn't be resolved
            final ProviderInfo providerAuthorityInfo = this.getPackageManager()
                    .resolveContentProvider(fileProviderAuthority, PackageManager.GET_META_DATA);
            if (providerAuthorityInfo == null) {
                Log.w(TAG,
                        "Could not resolve file provider authority : " + fileProviderAuthority
                                + ". Sharing of files captured not supported then. "
                                + "See http://maoni.rm3l.org/ for setup instructions.");
            } else {
                if (mScreenshotFilePath != null) {
                    screenshotFile = new File(mScreenshotFilePath.toString());
                    screenshotUri = FileProvider.getUriForFile(this, fileProviderAuthority, screenshotFile);
                    grantUriPermission(intent.getComponent().getPackageName(), screenshotUri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                if (logsFile != null) {
                    logsUri = FileProvider.getUriForFile(this, fileProviderAuthority, logsFile);
                    grantUriPermission(intent.getComponent().getPackageName(), logsUri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            }
        }

        //Construct the feedback object and call the actual implementation
        final Feedback feedback = new Feedback(mFeedbackUniqueId, this, mAppInfo, contentText,
                includeScreenshot, screenshotUri, screenshotFile, includeLogs, logsUri, logsFile,
                mSharedPreferences);
        if (mListener != null) {
            if (mListener.onSendButtonClicked(feedback)) {
                finish();
            } // else do *not* finish the activity
        } else {
            finish();
        }
    } //else do nothing - this is up to the callback implementation
}

From source file:com.ereinecke.eatsafe.MainActivity.java

private void launchPhotoIntent(int whichPhoto) {

    Logd(LOG_TAG, "Launching intent for photo #" + whichPhoto);
    // create Intent to take a picture and return control to the calling application
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

        // Create the File where the photo should go
        File photoFile = openOutputMediaFile();
        Logd(LOG_TAG, "photoReceived: " + photoReceived);

        if (photoFile != null) {

            Uri photoUri = StreamProvider.getUriForFile("com.ereinecke.eatsafe.fileprovider", photoFile);
            try {
                Logd(LOG_TAG, "photoUri: " + photoUri.toString());
            } catch (Exception e) {
                Logd(LOG_TAG, "photoUri is null: " + e.getMessage());
            }/*from   w ww.java  2 s .c o  m*/
            // set the image file name
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            takePictureIntent.putExtra(Constants.WHICH_PHOTO, whichPhoto);
            takePictureIntent
                    .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            // start the image capture Intent
            startActivityForResult(takePictureIntent, Constants.CAMERA_IMAGE_REQUEST);
        }
    }
}

From source file:it.feio.android.omninotes.DetailFragment.java

private void initViewAttachments() {

    // Attachments position based on preferences
    if (prefs.getBoolean(Constants.PREF_ATTANCHEMENTS_ON_BOTTOM, false)) {
        attachmentsBelow.inflate();//  w  w w  . j  a  va2  s . c  om
    } else {
        attachmentsAbove.inflate();
    }
    mGridView = (ExpandableHeightGridView) root.findViewById(R.id.gridview);

    // Some fields can be filled by third party application and are always shown
    mAttachmentAdapter = new AttachmentAdapter(mainActivity, noteTmp.getAttachmentsList(), mGridView);

    // Initialzation of gridview for images
    mGridView.setAdapter(mAttachmentAdapter);
    mGridView.autoresize();

    // Click events for images in gridview (zooms image)
    mGridView.setOnItemClickListener((parent, v, position, id) -> {
        Attachment attachment = (Attachment) parent.getAdapter().getItem(position);
        Uri uri = attachment.getUri();
        Intent attachmentIntent;
        if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) {

            attachmentIntent = new Intent(Intent.ACTION_VIEW);
            attachmentIntent.setDataAndType(uri, StorageHelper.getMimeType(mainActivity, attachment.getUri()));
            attachmentIntent
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (IntentChecker.isAvailable(mainActivity.getApplicationContext(), attachmentIntent, null)) {
                startActivity(attachmentIntent);
            } else {
                mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN);
            }

            // Media files will be opened in internal gallery
        } else if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) {
            // Title
            noteTmp.setTitle(getNoteTitle());
            noteTmp.setContent(getNoteContent());
            String title1 = TextHelper.parseTitleAndContent(mainActivity, noteTmp)[0].toString();
            // Images
            int clickedImage = 0;
            ArrayList<Attachment> images = new ArrayList<>();
            for (Attachment mAttachment : noteTmp.getAttachmentsList()) {
                if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
                    images.add(mAttachment);
                    if (mAttachment.equals(attachment)) {
                        clickedImage = images.size() - 1;
                    }
                }
            }
            // Intent
            attachmentIntent = new Intent(mainActivity, GalleryActivity.class);
            attachmentIntent.putExtra(Constants.GALLERY_TITLE, title1);
            attachmentIntent.putParcelableArrayListExtra(Constants.GALLERY_IMAGES, images);
            attachmentIntent.putExtra(Constants.GALLERY_CLICKED_IMAGE, clickedImage);
            startActivity(attachmentIntent);

        } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) {
            playback(v, attachment.getUri());
        }

    });

    mGridView.setOnItemLongClickListener((parent, v, position, id) -> {

        // To avoid deleting audio attachment during playback
        if (mPlayer != null)
            return false;

        List<String> items = Arrays.asList(getResources().getStringArray(R.array.attachments_actions));
        if (!Constants.MIME_TYPE_SKETCH.equals(mAttachmentAdapter.getItem(position).getMime_type())) {
            items = items.subList(0, items.size() - 1);
        }

        new MaterialDialog.Builder(mainActivity).title(mAttachmentAdapter.getItem(position).getName())
                .items(items.toArray(new String[items.size()]))
                .itemsCallback((materialDialog, view, i, charSequence) -> performAttachmentAction(position, i))
                .build().show();
        return true;
    });
}

From source file:com.tct.mail.browse.MessageAttachmentBar.java

private void importXvcard(Attachment attachment, final String type) {
    new AsyncTask<Attachment, Void, Uri>() {

        @Override/*from   w w  w.  j av a 2 s .co  m*/
        protected Uri doInBackground(Attachment... params) {
            final Attachment attach = params[0];
            final String[] filenames = mContext.fileList();
            for (String file : filenames) {
                if (file.endsWith(".vcf")) {
                    mContext.deleteFile(file);
                }
            }
            try {
                InputStream in = null;
                OutputStream out = null;
                try {
                    in = mContext.getContentResolver().openInputStream(attach.contentUri);
                    out = mContext.openFileOutput(attach.getName(), Context.MODE_WORLD_READABLE);
                    byte[] buf = new byte[8096];
                    int seg = 0;
                    while ((seg = in.read(buf)) != -1) {
                        out.write(buf, 0, seg);
                    }
                } finally {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                }
            } catch (FileNotFoundException e) {
                LogUtils.e(LOG_TAG, "importVCard, file not found " + attach + ", exception ", e);
            } catch (IOException e) {
                LogUtils.e(LOG_TAG, "importVCard, ioexception " + attach + ", exception ", e);
            } catch (Exception e) {
                LogUtils.e(LOG_TAG, "importVCard, unknown errror ", e);
            }
            final File tempVCard = mContext.getFileStreamPath(attach.getName());
            if (!tempVCard.exists() || tempVCard.length() <= 0) {
                LogUtils.e(LOG_TAG, "importVCard, file is not exists or empty " + tempVCard);
                return null;
            }
            return Uri.fromFile(tempVCard);
        }

        @Override
        protected void onPostExecute(Uri uri) {
            super.onPostExecute(uri);
            if (uri == null)
                return;
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            Utils.setIntentDataAndTypeAndNormalize(intent, uri, type);
            try {
                getContext().startActivity(intent);
            } catch (ActivityNotFoundException e) {
                // couldn't find activity for View intent
                LogUtils.e(LOG_TAG, e, "Couldn't find Activity for intent");
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                int dialogMessage = R.string.no_application_found;
                builder.setTitle(R.string.more_info_attachment).setMessage(dialogMessage).show();
            }
        }
    }.execute(attachment);
}

From source file:com.orange.ocara.ui.activity.ResultAuditActivity.java

/**
 * To share a document by its path.<br/>
 * This will send a share intent./*from   www  .j a v a2 s.c  om*/
 *
 * @param path the file path to share
 */
private void shareDocument(String path) {
    // create an intent, so the user can choose which application he/she wants to use to share this file
    final Intent intent = ShareCompat.IntentBuilder.from(this)
            .setType(MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)))
            .setStream(FileProvider.getUriForFile(this, "com.orange.ocara", exportFile))
            .setChooserTitle("How do you want to share?").createChooserIntent()
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    startActivityForResult(intent, ACTION_SHARE_DOCUMENT);
}

From source file:com.almalence.opencam.Fragment.java

@TargetApi(19)
@Override/*from  w w w. j a v  a  2  s . c  o  m*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CHOOSE_FOLDER_CODE) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.instance);
        if (resultCode == Activity.RESULT_OK) {
            Uri treeUri = data.getData();

            getActivity().getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            prefs.edit().putString(ApplicationScreen.sSavePathPref, treeUri.toString()).commit();
        } else {
            prefs.edit().putString(ApplicationScreen.sSaveToPref, "0").commit();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

From source file:dev.dworks.apps.anexplorer.fragment.DirectoryFragment.java

private void onShareDocuments(ArrayList<DocumentInfo> docs) {
    Intent intent;//  w ww . ja v  a2 s. c  om
    if (docs.size() == 1) {
        final DocumentInfo doc = docs.get(0);

        intent = new Intent(Intent.ACTION_SEND);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setType(doc.mimeType);
        intent.putExtra(Intent.EXTRA_STREAM, doc.derivedUri);

    } else if (docs.size() > 1) {
        intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // intent.addCategory(Intent.CATEGORY_DEFAULT);

        final ArrayList<String> mimeTypes = Lists.newArrayList();
        final ArrayList<Uri> uris = Lists.newArrayList();
        for (DocumentInfo doc : docs) {
            mimeTypes.add(doc.mimeType);
            uris.add(doc.derivedUri);
        }

        intent.setType(findCommonMimeType(mimeTypes));
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

    } else {
        return;
    }

    intent = Intent.createChooser(intent, getActivity().getText(R.string.share_via));
    startActivity(intent);
}

From source file:com.dycody.android.idealnote.DetailFragment.java

private void initViewAttachments() {

    // Attachments position based on preferences
    if (prefs.getBoolean(Constants.PREF_ATTANCHEMENTS_ON_BOTTOM, false)) {
        attachmentsBelow.inflate();/*from  www  . ja v  a 2  s .  c om*/
    } else {
        attachmentsAbove.inflate();
    }
    mGridView = (ExpandableHeightGridView) root.findViewById(R.id.gridview);

    // Some fields can be filled by third party application and are always shown
    mAttachmentAdapter = new AttachmentAdapter(mainActivity, noteTmp.getAttachmentsList(), mGridView);

    // Initialzation of gridview for images
    mGridView.setAdapter(mAttachmentAdapter);
    mGridView.autoresize();

    // Click events for images in gridview (zooms image)
    mGridView.setOnItemClickListener((parent, v, position, id) -> {
        Attachment attachment = (Attachment) parent.getAdapter().getItem(position);
        Uri uri = attachment.getUri();
        Intent attachmentIntent;
        if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) {

            attachmentIntent = new Intent(Intent.ACTION_VIEW);
            attachmentIntent.setDataAndType(uri, StorageHelper.getMimeType(mainActivity, attachment.getUri()));
            attachmentIntent
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (IntentChecker.isAvailable(mainActivity.getApplicationContext(), attachmentIntent, null)) {
                startActivity(attachmentIntent);
            } else {
                Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, Toast.LENGTH_SHORT)
                        .show();
                //mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN);
            }

            // Media files will be opened in internal gallery
        } else if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) {
            // Title
            noteTmp.setTitle(getNoteTitle());
            noteTmp.setContent(getNoteContent());
            String title1 = TextHelper.parseTitleAndContent(mainActivity, noteTmp)[0].toString();
            // Images
            int clickedImage = 0;
            ArrayList<Attachment> images = new ArrayList<>();
            for (Attachment mAttachment : noteTmp.getAttachmentsList()) {
                if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
                    images.add(mAttachment);
                    if (mAttachment.equals(attachment)) {
                        clickedImage = images.size() - 1;
                    }
                }
            }
            // Intent
            attachmentIntent = new Intent(mainActivity, GalleryActivity.class);
            attachmentIntent.putExtra(Constants.GALLERY_TITLE, title1);
            attachmentIntent.putParcelableArrayListExtra(Constants.GALLERY_IMAGES, images);
            attachmentIntent.putExtra(Constants.GALLERY_CLICKED_IMAGE, clickedImage);
            startActivity(attachmentIntent);

        } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) {
            playback(v, attachment.getUri());
        }

    });

    mGridView.setOnItemLongClickListener((parent, v, position, id) -> {
        // To avoid deleting audio attachment during playback
        if (mPlayer != null)
            return false;
        List<String> items = Arrays.asList(getResources().getStringArray(R.array.attachments_actions));
        if (!Constants.MIME_TYPE_SKETCH.equals(mAttachmentAdapter.getItem(position).getMime_type())) {
            items = items.subList(0, items.size() - 1);
        }
        Attachment attachment = mAttachmentAdapter.getItem(position);
        new MaterialDialog.Builder(mainActivity)
                .title(attachment.getName() + " (" + AttachmentsHelper.getSize(attachment) + ")")
                .items(items.toArray(new String[items.size()]))
                .itemsCallback((materialDialog, view, i, charSequence) -> performAttachmentAction(position, i))
                .build().show();
        return true;
    });
}

From source file:org.glucosio.android.activity.MainActivity.java

public void showShareDialog(Uri uri) {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setData(uri);/* www. j  a v a 2  s  .com*/
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    shareIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    shareIntent.setType("*/*");
    startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share_using)));
}