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:cz.maresmar.sfm.view.user.UserDetailFragment.java

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

    switch (requestCode) {
    case PICK_PROFILE_PICTURE:
        if (resultCode == Activity.RESULT_OK) {
            Timber.i("Profile picture selected");

            // Try to crop image (not every Android support it)
            try {
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(data.getData(), data.getType()); // Push selected picture to crop
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("return-data", true);
                intent.putExtra("finishActivityOnSaveCompleted", true);
                startActivityForResult(//w  w w  .  jav a 2  s .  co  m
                        Intent.createChooser(intent, getString(R.string.user_crop_picture_dialog)),
                        CROP_PROFILE_PICTURE);
            } catch (ActivityNotFoundException e) {
                Timber.w(e, "No cropping activity found");
            }

            // Save selected image
            new PictureLoaderAsyncTask(this).execute(data.getData());
        }
        break;
    case CROP_PROFILE_PICTURE:
        if (resultCode == Activity.RESULT_OK && data.getExtras() != null) {
            Bitmap resBitmap = data.getExtras().getParcelable("data");
            if (resBitmap != null) {
                Timber.i("User picture cropped");
                new PictureCropperAsyncTask(this).execute(resBitmap);
                break;
            }
        }
        Timber.w("Cropping wasn't successful (result code: %d)", requestCode);
        break;
    default:
        throw new UnsupportedOperationException("Unknown action request " + requestCode);
    }
}

From source file:com.osama.cryptofm.filemanager.listview.FileSelectionManagement.java

void openFile(final String filename) {
    if (SharedData.IS_IN_COPY_MODE) {
        return;/*  w w w .j a  v a 2 s.  co m*/
    }
    if (FileUtils.getExtension(filename).equals("pgp")) {
        Log.d(TAG, "openFile: File name is: " + filename);
        if (SharedData.KEY_PASSWORD == null) {
            final Dialog dialog = new Dialog(mContext);
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.password_dialog_layout);
            dialog.show();
            dialog.findViewById(R.id.cancel_decrypt_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            final EditText editText = (EditText) dialog.findViewById(R.id.key_password);
            dialog.findViewById(R.id.decrypt_file_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (editText.getText().length() < 1) {
                        editText.setError("please give me your encryption password");
                        return;
                    } else {
                        SharedData.KEY_PASSWORD = editText.getText().toString();
                        dialog.dismiss();
                        new DecryptTask(mContext, mFileListAdapter, SharedData.DB_PASSWWORD,
                                SharedData.USERNAME, FileUtils.CURRENT_PATH + filename, SharedData.KEY_PASSWORD)
                                        .execute();
                    }

                }
            });
        } else {
            new DecryptTask(mContext, mFileListAdapter, SharedData.DB_PASSWWORD, SharedData.USERNAME,
                    FileUtils.CURRENT_PATH + filename, SharedData.KEY_PASSWORD).execute();
        }

    } else {
        //open file
        if (SharedData.EXTERNAL_SDCARD_ROOT_PATH != null
                && FileUtils.CURRENT_PATH.contains(SharedData.EXTERNAL_SDCARD_ROOT_PATH)) {
            //open the document file
            DocumentFile file = FileDocumentUtils.getDocumentFile(FileUtils.getFile(filename));
            Intent intent = new Intent();
            intent.setDataAndType(file.getUri(), file.getType());
            intent.setAction(Intent.ACTION_VIEW);
            Intent x = Intent.createChooser(intent, "Open with");
            mContext.startActivity(x);
            return;
        }
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FileUtils.getExtension(filename));

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            Uri uri = FileProvider.getUriForFile(mContext,
                    mContext.getApplicationContext().getPackageName() + ".provider",
                    FileUtils.getFile(filename));
            intent.setDataAndType(uri, mimeType);
        } else {
            intent.setDataAndType(Uri.fromFile(FileUtils.getFile(filename)), mimeType);
        }
        intent.setAction(Intent.ACTION_VIEW);
        Intent x = Intent.createChooser(intent, "Open with: ");
        mContext.startActivity(x);
    }
}

From source file:com.android.gallery3d.gadget.WidgetConfigure.java

private void setChoosenPhoto(final Intent data) {
    AsyncTask.execute(new Runnable() {
        @Override/*  www.ja v  a  2 s  .  com*/
        public void run() {
            Resources res = getResources();

            float width = res.getDimension(R.dimen.appwidget_width);
            float height = res.getDimension(R.dimen.appwidget_height);

            // We try to crop a larger image (by scale factor), but there is still
            // a bound on the binder limit.
            float scale = Math.min(WIDGET_SCALE_FACTOR, MAX_WIDGET_SIDE / Math.max(width, height));

            int widgetWidth = Math.round(width * scale);
            int widgetHeight = Math.round(height * scale);

            File cropSrc = new File(getCacheDir(), "crop_source.png");
            File cropDst = new File(getCacheDir(), "crop_dest.png");
            mPickedItem = data.getData();
            if (!copyUriToFile(mPickedItem, cropSrc)) {
                setResult(Activity.RESULT_CANCELED);
                finish();
                return;
            }

            mCropSrc = FileProvider.getUriForFile(WidgetConfigure.this, "com.android.gallery3d.fileprovider",
                    new File(cropSrc.getAbsolutePath()));
            mCropDst = FileProvider.getUriForFile(WidgetConfigure.this, "com.android.gallery3d.fileprovider",
                    new File(cropDst.getAbsolutePath()));

            Intent request = new Intent(CropActivity.CROP_ACTION).putExtra(CropExtras.KEY_OUTPUT_X, widgetWidth)
                    .putExtra(CropExtras.KEY_OUTPUT_Y, widgetHeight)
                    .putExtra(CropExtras.KEY_ASPECT_X, widgetWidth)
                    .putExtra(CropExtras.KEY_ASPECT_Y, widgetHeight)
                    .putExtra(CropExtras.KEY_SCALE_UP_IF_NEEDED, true).putExtra(CropExtras.KEY_SCALE, true)
                    .putExtra(CropExtras.KEY_RETURN_DATA, false).setDataAndType(mCropSrc, "image/*")
                    .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            request.putExtra(MediaStore.EXTRA_OUTPUT, mCropDst);
            request.setClipData(ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, mCropDst));
            startActivityForResult(request, REQUEST_CROP_IMAGE);
        }
    });
}

From source file:com.osama.cryptofm.tasks.DecryptTask.java

@Override
protected void onPostExecute(String s) {
    SharedData.CURRENT_RUNNING_OPERATIONS.clear();

    if (singleFileMode) {
        if (s.equals(DECRYPTION_SUCCESS_MESSAGE)) {
            singleModeDialog.dismiss();//from  w w w.  ja v a 2s .co m
            Log.d(TAG, "onPostExecute: destination filename is: " + destFilename);
            //open file
            String mimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(FileUtils.getExtension(destFilename));

            Intent intent = new Intent();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                Uri uri = null;
                try {
                    uri = FileProvider.getUriForFile(mContext,
                            mContext.getApplicationContext().getPackageName() + ".provider",
                            TasksFileUtils.getFile(destFilename));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                intent.setDataAndType(uri, mimeType);
            } else {
                try {
                    intent.setDataAndType(Uri.fromFile(TasksFileUtils.getFile(destFilename)), mimeType);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            intent.setAction(Intent.ACTION_VIEW);
            Intent x = Intent.createChooser(intent, "Open with: ");
            mContext.startActivity(x);
        } else {
            singleModeDialog.dismiss();
            Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
        }
    } else {
        mProgressDialog.dismiss("Decryption completed");
        SharedData.CURRENT_RUNNING_OPERATIONS.clear();
        Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
        UiUtils.reloadData(mContext, mAdapter);
    }

}

From source file:com.just.agentweb.AgentWebUtils.java

static void grantPermissions(Context context, Intent intent, Uri uri, boolean writeAble) {

    int flag = Intent.FLAG_GRANT_READ_URI_PERMISSION;
    if (writeAble) {
        flag |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
    }/*from w ww.j a  v a2 s.c o m*/
    intent.addFlags(flag);
    List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        context.grantUriPermission(packageName, uri, flag);
    }
}

From source file:com.jalotsav.aalayamnavjivan.ActvtyBookView.java

private void shareBook() {
    try {//w w  w . jav  a  2s  .  c  o  m

        File mBookFilePathLocal = new File(mBookPathLocal);
        if (mBookFilePathLocal.exists()) {

            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.setType("application/pdf");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mBookFilePathLocal));
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(shareIntent,
                    getString(R.string.share_appname_book_3dots, getString(R.string.app_name))));
        } else
            Snackbar.make(mCrdntrlyot, mBookNotFound, Snackbar.LENGTH_LONG).show();
    } catch (Exception e) {
        e.printStackTrace();
        Snackbar.make(mCrdntrlyot, mBookNotFound, Snackbar.LENGTH_LONG).show();
    }
}

From source file:com.android.settings.users.EditUserPhotoController.java

private void appendOutputExtra(Intent intent, Uri pictureUri) {
    intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setClipData(ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, pictureUri));
}

From source file:com.duy.pascal.ui.file.FileExplorerAction.java

private void shareFile() {
    if (mCheckedList.isEmpty() || mShareActionProvider == null)
        return;/*from  ww  w  .  jav a  2s .  c  o  m*/
    try {
        Intent shareIntent = new Intent();
        if (mCheckedList.size() == 1) {
            File file = new File(mCheckedList.get(0).getPath());
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.setType(MimeTypes.getInstance().getMimeType(file.getPath()));

            Uri fileUri;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                fileUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider",
                        file);
            } else {
                fileUri = Uri.fromFile(file);
            }
            shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);

            ArrayList<Uri> streams = new ArrayList<>();
            for (File file : mCheckedList) {
                File File = new File(file.getPath());
                Uri fileUri;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                    fileUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider",
                            File);
                } else {
                    fileUri = Uri.fromFile(File);
                }
                streams.add(fileUri);
            }

            shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, streams);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        mShareActionProvider.setShareIntent(shareIntent);
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
}

From source file:libcore.tzdata.update_test_app.installupdatetestapp.MainActivity.java

private void sendIntent(File contentFile, String action, String version, String required, String sig) {
    Intent i = new Intent();
    i.setAction(action);// w ww . j a va 2  s . c  om
    Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),
            "libcore.tzdata.update_test_app.fileprovider", contentFile);
    i.setData(contentUri);
    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    i.putExtra(EXTRA_VERSION_NUMBER, version);
    i.putExtra(EXTRA_REQUIRED_HASH, required);
    i.putExtra(EXTRA_SIGNATURE, sig);
    sendBroadcast(i);
}

From source file:com.frostwire.android.gui.util.UIUtils.java

/**
 * Opens the given file with the default Android activity for that File and
 * mime type./*from   www  . ja  v a 2  s . c  om*/
 */
public static void openFile(Context context, String filePath, String mime, boolean useFileProvider) {
    try {
        if (filePath != null && !openAudioInternal(context, filePath)) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(getFileUri(context, filePath, useFileProvider), Intent.normalizeMimeType(mime));
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (mime != null && mime.contains("video")) {
                if (MusicUtils.isPlaying()) {
                    MusicUtils.playOrPause();
                }
                UXStats.instance().log(UXAction.LIBRARY_VIDEO_PLAY);
            }
            context.startActivity(i);
        }
    } catch (Throwable e) {
        UIUtils.showShortMessage(context, R.string.cant_open_file);
        LOG.error("Failed to open file: " + filePath, e);
    }
}