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:de.tap.easy_xkcd.fragments.comics.FavoritesFragment.java

private void exportFavorites() {
    //Export the full favorites list as text
    StringBuilder sb = new StringBuilder();
    String newline = System.getProperty("line.separator");
    for (int i = 0; i < favorites.length; i++) {
        sb.append(favorites[i]).append(" - ");
        sb.append(prefHelper.getTitle(favorites[i]));
        sb.append(newline);// ww  w  . jav a  2s  . co m
    }
    try {
        File sdCard = prefHelper.getOfflinePath();
        File dir = new File(sdCard.getAbsolutePath() + "/easy xkcd");
        File file = new File(dir, "favorites.txt");
        FileWriter writer = new FileWriter(file);
        writer.append(sb.toString());
        writer.flush();
        writer.close();
        //Provide option to send to any app that accepts text/plain content
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        Uri uri = FileProvider.getUriForFile(getActivity(), "de.tap.easy_xkcd.fileProvider", file);
        sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.pref_export)));
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), "Export failed", Toast.LENGTH_SHORT).show();
    }
}

From source file:me.myatminsoe.myansms.Message.java

/**
 * Fetch MMS parts.//from   w  ww.  ja  v  a2 s.  c om
 *
 * @param context {@link Context}
 */
private void fetchMmsParts(final Context context) {
    final ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(URI_PARTS, null, PROJECTION_PARTS[INDEX_MID] + " = ?",
            new String[] { String.valueOf(id) }, null);
    if (cursor == null || !cursor.moveToFirst()) {
        return;
    }
    final int iID = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_ID]);
    final int iCT = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_CT]);
    final int iText = cursor.getColumnIndex("text");
    do {
        final int pid = cursor.getInt(iID);
        final String ct = cursor.getString(iCT);

        // get part
        InputStream is = null;

        final Uri uri = ContentUris.withAppendedId(URI_PARTS, pid);
        if (uri == null) {

            continue;
        }
        try {
            is = cr.openInputStream(uri);
        } catch (IOException | NullPointerException e) {

        }
        if (is == null) {

            if (iText >= 0 && ct != null && ct.startsWith("text/")) {
                body = cursor.getString(iText);
            }
            continue;
        }
        if (ct == null) {
            continue;
        }
        if (ct.startsWith("image/")) {
            picture = BitmapFactory.decodeStream(is);
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("video/") || ct.startsWith("audio/")) {
            picture = BITMAP_PLAY;
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("text/")) {
            body = fetchPart(is);
        }

        try {
            is.close();
        } catch (IOException e) {
        } // Ignore
    } while (cursor.moveToNext());
}

From source file:com.nnm.smsviet.Message.java

/**
 * Fetch MMS parts./*from   w  w w.  j  a v  a 2s .  co m*/
 * 
 * @param context
 *            {@link Context}
 */
private void fetchMmsParts(final Context context) {
    final ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(URI_PARTS, null, PROJECTION_PARTS[INDEX_MID] + " = ?",
            new String[] { String.valueOf(this.id) }, null);
    if (cursor == null || !cursor.moveToFirst()) {
        return;
    }
    final int iID = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_ID]);
    final int iCT = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_CT]);
    final int iText = cursor.getColumnIndex("text");
    do {
        final int pid = cursor.getInt(iID);
        final String ct = cursor.getString(iCT);
        Log.d(TAG, "part: " + pid + " " + ct);

        // get part
        InputStream is = null;

        final Uri uri = ContentUris.withAppendedId(URI_PARTS, pid);
        try {
            is = cr.openInputStream(uri);
        } catch (IOException e) {
            Log.e(TAG, "Failed to load part data", e);
        }
        if (is == null) {
            Log.i(TAG, "InputStream for part " + pid + " is null");
            if (iText >= 0 && ct.startsWith("text/")) {
                this.body = cursor.getString(iText);
            }
            continue;
        }
        if (ct == null) {
            continue;
        }
        if (ct.startsWith("image/")) {
            this.picture = BitmapFactory.decodeStream(is);
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            this.contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("video/") || ct.startsWith("audio/")) {
            this.picture = BITMAP_PLAY;
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            this.contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("text/")) {
            this.body = this.fetchPart(is);
        }

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                Log.e(TAG, "Failed to close stream", e);
            } // Ignore
        }
    } while (cursor.moveToNext());
}

From source file:com.android.messaging.ui.UIIntentsImpl.java

@Override
public void launchSaveVCardToContactsActivity(final Context context, final Uri vcardUri) {
    Assert.isTrue(MediaScratchFileProvider.isMediaScratchSpaceUri(vcardUri));
    final Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(vcardUri, ContentType.TEXT_VCARD.toLowerCase());
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startExternalActivity(context, intent);
}

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

@Override
public void viewAttachment() {
    if (mAttachment.contentUri == null) {
        LogUtils.e(LOG_TAG, "viewAttachment with null content uri");
        return;//from w  w  w.j  a  va  2 s .  c  om
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

    final String contentType = mAttachment.getContentType();
    Utils.setIntentDataAndTypeAndNormalize(intent, mAttachment.contentUri, contentType);

    // For EML files, we want to open our dedicated
    // viewer rather than let any activity open it.
    if (MimeType.isEmlMimeType(contentType)) {
        intent.setPackage(getContext().getPackageName());
        intent.putExtra(AccountFeedbackActivity.EXTRA_ACCOUNT_URI, mAccount != null ? mAccount.uri : null);
    }

    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");
    }
}

From source file:com.orpheusdroid.screenrecorder.adapter.VideoRecyclerAdapter.java

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Video video = videos.get(position);
    switch (holder.getItemViewType()) {
    case VIEW_ITEM:
        final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
        //Set video file name
        itemViewHolder.tv_fileName.setText(video.getFileName());
        //If thumbnail has failed for some reason, set empty image resource to imageview
        if (videos.get(position).getThumbnail() != null) {
            itemViewHolder.iv_thumbnail.setImageBitmap(video.getThumbnail());
        } else {// ww  w  .j a v  a  2  s . c  o m
            itemViewHolder.iv_thumbnail.setImageResource(0);
            Log.d(Const.TAG, "thumbnail error");
        }

        // Hide the play image over thumbnail and overflow menu if multiselect enabled
        if (isMultiSelect) {
            itemViewHolder.iv_play.setVisibility(View.INVISIBLE);
            itemViewHolder.overflow.setVisibility(View.INVISIBLE);
        } else {
            itemViewHolder.iv_play.setVisibility(View.VISIBLE);
            itemViewHolder.overflow.setVisibility(View.VISIBLE);
        }

        // Set foreground color to identify selected items
        if (video.isSelected()) {
            itemViewHolder.selectableFrame.setForeground(
                    new ColorDrawable(ContextCompat.getColor(context, R.color.multiSelectColor)));
        } else {
            itemViewHolder.selectableFrame.setForeground(
                    new ColorDrawable(ContextCompat.getColor(context, android.R.color.transparent)));
        }

        itemViewHolder.overflow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popupMenu = new PopupMenu(context, view);
                popupMenu.inflate(R.menu.popupmenu);
                popupMenu.show();
                popupMenu.getMenu().getItem(3).setEnabled(PreferenceManager.getDefaultSharedPreferences(context)
                        .getBoolean(context.getString(R.string.preference_save_gif_key), false));
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                        case R.id.share:
                            shareVideo(itemViewHolder.getAdapterPosition());
                            break;
                        case R.id.delete:
                            confirmDelete(holder.getAdapterPosition());
                            break;
                        case R.id.edit:
                            Toast.makeText(context, "Edit video for " + itemViewHolder.getAdapterPosition(),
                                    Toast.LENGTH_SHORT).show();

                            Intent editIntent = new Intent(context, EditVideoActivity.class);
                            editIntent.putExtra(Const.VIDEO_EDIT_URI_KEY,
                                    Uri.fromFile(video.getFile()).toString());
                            Log.d(Const.TAG, "Uri: " + Uri.fromFile(video.getFile()));
                            videosListFragment.startActivityForResult(editIntent,
                                    Const.VIDEO_EDIT_REQUEST_CODE);
                            break;
                        case R.id.savegif:
                            Mp4toGIFConverter gif = new Mp4toGIFConverter(context);
                            gif.setVideoUri(Uri.fromFile(video.getFile()));
                            gif.convertToGif();
                        }
                        return true;
                    }
                });
            }
        });

        //Show user a chooser to play the video with
        itemViewHolder.videoCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Video video = videos.get(itemViewHolder.getAdapterPosition());

                // If multiselect is enabled, select the items pressed by user
                if (isMultiSelect) {

                    // main count of the selected items
                    // If the video is already selected, reduce count else increment count
                    if (video.isSelected())
                        count--;
                    else
                        count++;

                    // Enable disable selection based on previous choice
                    video.setSelected(!video.isSelected());
                    notifyDataSetChanged();
                    mActionMode.setTitle("" + count);

                    // If the count is 0, disable muliselect
                    if (count == 0)
                        setMultiSelect(false);
                    return;
                }

                File videoFile = video.getFile();
                Log.d("Videos List", "video position clicked: " + itemViewHolder.getAdapterPosition());

                Uri fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider",
                        videoFile);
                Log.d(Const.TAG, fileUri.toString());
                Intent openVideoIntent = new Intent();
                openVideoIntent.setAction(Intent.ACTION_VIEW).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        .setDataAndType(fileUri, context.getContentResolver().getType(fileUri));
                context.startActivity(openVideoIntent);
            }
        });

        // LongClickListener to enable multiselect
        itemViewHolder.videoCard.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (!isMultiSelect) {
                    setMultiSelect(true);
                    video.setSelected(true);
                    count++;
                    mActionMode.setTitle("" + count);
                    notifyDataSetChanged();
                }
                return true;
            }
        });

        break;
    case VIEW_SECTION:
        SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
        sectionViewHolder.section.setText(generateSectionTitle(video.getLastModified()));
        break;
    }
}

From source file:de.stadtrallye.rallyesoft.model.pictures.PictureManager.java

@TargetApi(19)
private void takePersistableUriPermissionApi19(Intent data, Uri uri) {
    final int takeFlags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION;
    // Check for the freshest data.
    context.getContentResolver().takePersistableUriPermission(uri, takeFlags);
}

From source file:com.amaze.carbonfilemanager.utils.files.Futils.java

public void openunknown(DocumentFile f, Context c, boolean forcechooser) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    String type = f.getType();/*from  w w  w .j ava  2s .  c  o m*/
    if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
        intent.setDataAndType(f.getUri(), type);
        Intent startintent;
        if (forcechooser)
            startintent = Intent.createChooser(intent, c.getResources().getString(R.string.openwith));
        else
            startintent = intent;
        try {
            c.startActivity(startintent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c);
        }
    } else {
        openWith(f, c);
    }

}

From source file:com.brq.wallet.activity.export.BackupToPdfActivity.java

private void sharePdf() {
    findViewById(R.id.btSharePdf).setEnabled(false);
    ((TextView) findViewById(R.id.tvStatus))
            .setText(getResources().getString(R.string.encrypted_pdf_backup_sharing));
    Uri uri = getUri();/*w  w  w . ja va 2 s  . c  o m*/

    String bodyText = getResources().getString(R.string.encrypted_pdf_backup_email_text);
    Intent intent = ShareCompat.IntentBuilder.from(this).setStream(uri)
            // uri from FileProvider
            .setType("application/pdf").setSubject(getSubject()).setText(bodyText).getIntent()
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    grantPermissions(intent, uri);
    startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.share_with)),
            SHARE_REQUEST_CODE);
}

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

@Receiver(actions = AuditExportService.EXPORT_SUCCESS, local = true, registerAt = Receiver.RegisterAt.OnResumeOnPause)
@UiThread(propagation = UiThread.Propagation.REUSE)
void onExportAuditDone(@Receiver.Extra String path) {
    setLoading(false);/*from   w  w  w  . ja  v  a  2s . co m*/

    exportFile = new File(path);

    switch (exportAction) {
    case EXPORT_ACTION_SHARE: {

        // 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);

        startActivity(intent);
        break;
    }

    case EXPORT_ACTION_SAVE: {
        createNewDocument(path);
        break;
    }
    }
}