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.android.gallery3d.app.PhotoPage.java

private static Intent createSharePanoramaIntent(Uri contentUri) {
    return new Intent(Intent.ACTION_SEND).setType(GalleryUtils.MIME_TYPE_PANORAMA360)
            .putExtra(Intent.EXTRA_STREAM, contentUri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}

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

private void onSubItemClick(int id) {
    final MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
    if (messageObject == null || parentActivity == null) {
        return;/*from w  ww .  jav a  2 s. c  o m*/
    }
    if (id == 1) {
        if (UserConfig.selectedAccount != currentAccount) {
            parentActivity.switchToAccount(currentAccount, true);
        }
        Bundle args = new Bundle();
        args.putBoolean("onlySelect", true);
        args.putInt("dialogsType", 3);
        DialogsActivity fragment = new DialogsActivity(args);
        final ArrayList<MessageObject> fmessages = new ArrayList<>();
        fmessages.add(messageObject);
        fragment.setDelegate((fragment1, dids, message, param) -> {
            if (dids.size() > 1 || dids.get(0) == UserConfig.getInstance(currentAccount).getClientUserId()
                    || message != null) {
                for (int a = 0; a < dids.size(); a++) {
                    long did = dids.get(a);
                    if (message != null) {
                        SendMessagesHelper.getInstance(currentAccount).sendMessage(message.toString(), did,
                                null, null, true, null, null, null);
                    }
                    SendMessagesHelper.getInstance(currentAccount).sendMessage(fmessages, did);
                }
                fragment1.finishFragment();
            } else {
                long did = dids.get(0);
                int lower_part = (int) did;
                int high_part = (int) (did >> 32);
                Bundle args1 = new Bundle();
                args1.putBoolean("scrollToTopOnResume", true);
                if (lower_part != 0) {
                    if (lower_part > 0) {
                        args1.putInt("user_id", lower_part);
                    } else if (lower_part < 0) {
                        args1.putInt("chat_id", -lower_part);
                    }
                } else {
                    args1.putInt("enc_id", high_part);
                }
                NotificationCenter.getInstance(currentAccount)
                        .postNotificationName(NotificationCenter.closeChats);
                ChatActivity chatActivity = new ChatActivity(args1);
                if (parentActivity.presentFragment(chatActivity, true, false)) {
                    chatActivity.showFieldPanelForForward(true, fmessages);
                } else {
                    fragment1.finishFragment();
                }
            }
        });
        parentActivity.presentFragment(fragment);
        dismiss();
    } else if (id == 2) {
        try {
            File f = null;
            boolean isVideo = false;

            if (!TextUtils.isEmpty(messageObject.messageOwner.attachPath)) {
                f = new File(messageObject.messageOwner.attachPath);
                if (!f.exists()) {
                    f = null;
                }
            }
            if (f == null) {
                f = FileLoader.getPathToMessage(messageObject.messageOwner);
            }

            if (f.exists()) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                if (messageObject != null) {
                    intent.setType(messageObject.getMimeType());
                } else {
                    intent.setType("audio/mp3");
                }
                if (Build.VERSION.SDK_INT >= 24) {
                    try {
                        intent.putExtra(Intent.EXTRA_STREAM,
                                FileProvider.getUriForFile(ApplicationLoader.applicationContext,
                                        BuildConfig.APPLICATION_ID + ".provider", f));
                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    } catch (Exception ignore) {
                        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                    }
                } else {
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                }

                parentActivity.startActivityForResult(Intent.createChooser(intent,
                        LocaleController.getString("ShareFile", R.string.ShareFile)), 500);
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                builder.setMessage(LocaleController.getString("PleaseDownload", R.string.PleaseDownload));
                builder.show();
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    } else if (id == 3) {
        AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
        //builder.setMessage(LocaleController.formatString("AreYouSureDeleteAudio", R.string.AreYouSureDeleteAudio));
        builder.setTitle(LocaleController.getString("AppName", R.string.AppName));

        final boolean deleteForAll[] = new boolean[1];
        int lower_id = (int) messageObject.getDialogId();
        if (lower_id != 0) {
            TLRPC.Chat currentChat;
            TLRPC.User currentUser;
            if (lower_id > 0) {
                currentUser = MessagesController.getInstance(currentAccount).getUser(lower_id);
                currentChat = null;
            } else {
                currentUser = null;
                currentChat = MessagesController.getInstance(currentAccount).getChat(-lower_id);
            }
            if (currentUser != null || !ChatObject.isChannel(currentChat)) {
                boolean hasOutgoing = false;
                int currentDate = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
                if (currentUser != null
                        && currentUser.id != UserConfig.getInstance(currentAccount).getClientUserId()
                        || currentChat != null) {
                    if ((messageObject.messageOwner.action == null
                            || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionEmpty)
                            && messageObject.isOut()
                            && (currentDate - messageObject.messageOwner.date) <= 2 * 24 * 60 * 60) {
                        FrameLayout frameLayout = new FrameLayout(parentActivity);
                        CheckBoxCell cell = new CheckBoxCell(parentActivity, 1);
                        cell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
                        if (currentChat != null) {
                            cell.setText(LocaleController.getString("DeleteForAll", R.string.DeleteForAll), "",
                                    false, false);
                        } else {
                            cell.setText(LocaleController.formatString("DeleteForUser", R.string.DeleteForUser,
                                    UserObject.getFirstName(currentUser)), "", false, false);
                        }
                        cell.setPadding(
                                LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0,
                                LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0);
                        frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48,
                                Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0));
                        cell.setOnClickListener(v -> {
                            CheckBoxCell cell1 = (CheckBoxCell) v;
                            deleteForAll[0] = !deleteForAll[0];
                            cell1.setChecked(deleteForAll[0], true);
                        });
                        builder.setView(frameLayout);
                    }
                }
            }
        }
        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> {
            dismiss();
            ArrayList<Integer> arr = new ArrayList<>();
            arr.add(messageObject.getId());
            ArrayList<Long> random_ids = null;
            TLRPC.EncryptedChat encryptedChat = null;
            if ((int) messageObject.getDialogId() == 0 && messageObject.messageOwner.random_id != 0) {
                random_ids = new ArrayList<>();
                random_ids.add(messageObject.messageOwner.random_id);
                encryptedChat = MessagesController.getInstance(currentAccount)
                        .getEncryptedChat((int) (messageObject.getDialogId() >> 32));
            }
            MessagesController.getInstance(currentAccount).deleteMessages(arr, random_ids, encryptedChat,
                    messageObject.messageOwner.to_id.channel_id, deleteForAll[0]);
        });
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
        builder.show();
    } else if (id == 4) {
        if (UserConfig.selectedAccount != currentAccount) {
            parentActivity.switchToAccount(currentAccount, true);
        }

        Bundle args = new Bundle();
        long did = messageObject.getDialogId();
        int lower_part = (int) did;
        int high_id = (int) (did >> 32);
        if (lower_part != 0) {
            if (high_id == 1) {
                args.putInt("chat_id", lower_part);
            } else {
                if (lower_part > 0) {
                    args.putInt("user_id", lower_part);
                } else if (lower_part < 0) {
                    TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_part);
                    if (chat != null && chat.migrated_to != null) {
                        args.putInt("migrated_to", lower_part);
                        lower_part = -chat.migrated_to.channel_id;
                    }
                    args.putInt("chat_id", -lower_part);
                }
            }
        } else {
            args.putInt("enc_id", high_id);
        }
        args.putInt("message_id", messageObject.getId());
        NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats);
        parentActivity.presentFragment(new ChatActivity(args), false, false);
        dismiss();
    }
}

From source file:org.de.jmg.learn.MainActivity.java

@SuppressLint("NewApi")
private void takePersistableUri(Uri selectedUri, boolean force) throws Exception {
    if (Build.VERSION.SDK_INT >= 19) {
        try {/*from ww  w.j ava 2s.  c o  m*/
            final int takeFlags = (Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(selectedUri, takeFlags);
        } catch (Exception ex) {
            Log.e("takePersistableUri", "Error", ex);
            if (force)
                lib.ShowException(this, ex);
        }

    }
}

From source file:com.android.gallery3d.app.PhotoPage.java

private void launchTinyPlanet() {
    // Deep link into tiny planet
    MediaItem current = mModel.getMediaItem(0);
    Intent intent = new Intent(FilterShowActivity.TINY_PLANET_ACTION);
    intent.setClass(mActivity, FilterShowActivity.class);
    intent.setDataAndType(current.getContentUri(), current.getMimeType())
            .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.putExtra(FilterShowActivity.LAUNCH_FULLSCREEN, mActivity.isFullscreen());
    mActivity.startActivityForResult(intent, REQUEST_EDIT);
    overrideTransitionToEditor();/*from  w  w w.  j  ava2  s  .  c om*/
}

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

/**
 * Returns the intent with uri corresponding to specific {@link HybridFileParcelable} back to external app
 *//*from  w w w.j a  v  a  2  s .co 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.android.gallery3d.app.PhotoPage.java

private void launchPhotoEditor() {
    /// M: [BUG.ADD] abort editing photo if loading fail @{
    if (mModel != null && mModel.getLoadingState(0) == PhotoView.Model.LOADING_FAIL) {
        Log.i(TAG, "<launchPhotoEditor> abort editing photo if loading fail!");
        Toast.makeText(mActivity, mActivity.getString(R.string.cannot_load_image), Toast.LENGTH_SHORT).show();
        return;/*ww w  .ja  v a2  s .  c o m*/
    }
    /// @}
    MediaItem current = mModel.getMediaItem(0);
    if (current == null || (current.getSupportedOperations() & MediaObject.SUPPORT_EDIT) == 0) {
        return;
    }

    Intent intent = new Intent(ACTION_NEXTGEN_EDIT);

    /// M: [BUG.MODIFY] create new task when launch photo editor from camera
    // gallery and photo editor use same task stack @{
    /*
    intent.setDataAndType(current.getContentUri(), current.getMimeType())
          .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    */
    intent.setDataAndType(current.getContentUri(), current.getMimeType())
            .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
    /// @}
    if (mActivity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
            .size() == 0) {
        intent.setAction(Intent.ACTION_EDIT);
    }
    intent.putExtra(FilterShowActivity.LAUNCH_FULLSCREEN, mActivity.isFullscreen());
    /// M: [FEATURE.ADD] @{
    // for special image, no need to delete origin image when save, such as continuous shot
    ExtItem extItem = current.getExtItem();
    if (extItem != null && !extItem.isDeleteOriginFileAfterEdit()) {
        // if current photo is last image in continuous shot group, not
        // set NEED_SAVE_AS as true
        if (mModel instanceof PhotoDataAdapter) {
            int size = ((PhotoDataAdapter) mModel).getTotalCount();
            MediaData md = current.getMediaData();
            if (size == 1 && md.mediaType == MediaData.MediaType.NORMAL
                    && md.subType == MediaData.SubType.CONSHOT) {
                intent.putExtra(FilterShowActivity.NEED_SAVE_AS, false);
                Log.i(TAG, "<launchPhotoEditor> edit the last image in continuous shot group,"
                        + " not set NEED_SAVE_AS as true");
            } else {
                intent.putExtra(FilterShowActivity.NEED_SAVE_AS, true);
            }
        } else {
            intent.putExtra(FilterShowActivity.NEED_SAVE_AS, true);
        }
    }
    /// @}

    /// M: [BUG.MODIFY] @{
    // Make ChooserActivity and GalleryActivity in different tasks.
    /*
     * ((Activity)mActivity).startActivityForResult(Intent.createChooser(intent
     * , null), REQUEST_EDIT);
     */
    ((Activity) mActivity).startActivityForResult(
            Intent.createChooser(intent, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), REQUEST_EDIT);
    /// @}

    overrideTransitionToEditor();
}

From source file:dev.dworks.apps.anexplorer.DocumentsActivity.java

public void onDocumentPicked(DocumentInfo doc) {
    final FragmentManager fm = getFragmentManager();
    if (doc.isDirectory()) {
        mState.stack.push(doc);//w  w w  .j a  v a  2  s.com
        mState.stackTouched = true;
        onCurrentDirectoryChanged(ANIM_DOWN);
        final MoveFragment move = MoveFragment.get(fm);
        if (move != null) {
            move.setReplaceTarget(doc);
        }
    } else if (mState.action == ACTION_OPEN || mState.action == ACTION_GET_CONTENT) {
        // Explicit file picked, return
        new ExistingFinishTask(doc.derivedUri).executeOnExecutor(getCurrentExecutor());
    } else if (mState.action == ACTION_BROWSE) {

        /*if(doc.isZipFile()){
        mState.stack.push(doc);
        mState.stackTouched = true;
        onCurrentDirectoryChanged(ANIM_DOWN);
           return;
        }*/
        /*            final long token = Binder.clearCallingIdentity();
                    try {
                
                    } finally {
        Binder.restoreCallingIdentity(token);
                    }*/
        // Fall back to viewing
        final Intent view = new Intent(Intent.ACTION_VIEW);
        view.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        view.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        if (MimePredicate.mimeMatches(MimePredicate.SPECIAL_MIMES, doc.mimeType)) {
            try {
                File file = new File(doc.path);
                view.setDataAndType(Uri.fromFile(file), doc.mimeType);
            } catch (Exception e) {
                view.setDataAndType(doc.derivedUri, doc.mimeType);
            }
        } else {
            view.setDataAndType(doc.derivedUri, doc.mimeType);
        }

        try {
            startActivity(view);
        } catch (ActivityNotFoundException ex2) {
            Toast.makeText(this, R.string.toast_no_application, Toast.LENGTH_SHORT).show();
        }
    } else if (mState.action == ACTION_CREATE) {
        // Replace selected file
        SaveFragment.get(fm).setReplaceTarget(doc);
    } else if (mState.action == ACTION_MANAGE) {
        // First try managing the document; we expect manager to filter
        // based on authority, so we don't grant.
        final Intent manage = new Intent(DocumentsContract.ACTION_MANAGE_DOCUMENT);
        manage.setData(doc.derivedUri);

        try {
            startActivity(manage);
        } catch (ActivityNotFoundException ex) {
            // Fall back to viewing
            final Intent view = new Intent(Intent.ACTION_VIEW);
            view.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            view.setData(doc.derivedUri);

            try {
                startActivity(view);
            } catch (ActivityNotFoundException ex2) {
                Toast.makeText(this, R.string.toast_no_application, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

From source file:com.hivewallet.androidclient.wallet.ui.WalletActivity.java

private boolean archiveWalletBackup(@Nonnull final File file) {
    Uri shareableUri = null;//ww  w.  jav a 2s.  c o m
    try {
        shareableUri = FileProvider.getUriForFile(this, Constants.FILE_PROVIDER_AUTHORITY, file);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Backup file cannot be shared", e);
    }

    log.info("Shareable URI: {}", shareableUri);

    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_keys_dialog_mail_subject));
    intent.putExtra(Intent.EXTRA_TEXT,
            getString(R.string.export_keys_dialog_mail_text) + "\n\n"
                    + String.format(Constants.WEBMARKET_APP_URL, getPackageName()) + "\n\n"
                    + Constants.SOURCE_URL + '\n');
    intent.setType(Constants.MIMETYPE_WALLET_BACKUP);
    intent.putExtra(Intent.EXTRA_STREAM, shareableUri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        startActivity(Intent.createChooser(intent, getString(R.string.export_keys_dialog_mail_intent_chooser)));
        log.info("invoked chooser for archiving wallet backup");
        return true;
    } catch (final Exception x) {
        longToast(R.string.export_keys_dialog_mail_intent_failed);
        log.error("archiving wallet backup failed", x);
        return false;
    }
}

From source file:org.getlantern.firetweet.activity.support.ComposeActivity.java

private boolean pickImage() {
    final Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    try {//from w ww . j a v a2  s.  co  m
        startActivityForResult(intent, REQUEST_PICK_IMAGE);
    } catch (final ActivityNotFoundException e) {
        showErrorMessage(this, null, e, false);
        return false;
    }
    return true;
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

/** Starts an activity for picture attachment selection. */
@TargetApi(Build.VERSION_CODES.KITKAT)//from ww  w. j  a  v  a 2s  .  c o m
private void selectGalleryAttachment() {
    Intent pictureIntent;

    if (!MediaStorage.isStorageAccessFrameworkAvailable()) {
        pictureIntent = new Intent(Intent.ACTION_GET_CONTENT).putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                .addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        pictureIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    }

    pictureIntent.addCategory(Intent.CATEGORY_OPENABLE).setType("image/*")
            .addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION).putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

    startActivityForResult(pictureIntent, SELECT_ATTACHMENT_OPENABLE);
}