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.j4velin.encrypter.PlaintextFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.fragment_filelist, container, false);
    adapter = new FileAdapter(getContext(), new FileAdapter.ClickListener() {
        @Override//from  w ww.  j a v a 2 s  .  c om
        public void click(final File file) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(file.uri, file.mime);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
        }
    }, new FileAdapter.DeleteListener() {
        @Override
        public boolean delete(final File file) {
            boolean result = DocumentsContract.deleteDocument(getActivity().getContentResolver(), file.uri);
            if (!result) {
                java.io.File f = new java.io.File(file.uri.getPath());
                result = !f.exists() || f.delete();
            }
            if (!result) {
                Snackbar.make(((MainActivity) getActivity()).getCoordinatorLayout(),
                        getString(R.string.can_not_delete, file.name), Snackbar.LENGTH_LONG).show();
            }
            if (result && adapter.getSize() == 1) {
                // we're removing the last element -> hide the view
                ((MainActivity) getActivity()).showPlaintextLayout(false);
            }
            return result;
        }
    });
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setAdapter(adapter);
    return recyclerView;
}

From source file:com.android.cts.intent.sender.ContentTest.java

/**
 * This method will send an intent to a receiver in another profile.
 * This intent will have, in the ClipData, a uri whose associated file stores a message.
 * The receiver will read the message from the uri, and put it inside the result intent.
 *///from ww w.  j  av  a  2 s . c o m
public void testReceiverCanRead() throws Exception {
    Uri uri = getUriWithTextInFile("reading_test", MESSAGE);
    assertTrue(uri != null);
    Intent intent = new Intent(ACTION_READ_FROM_URI);
    intent.setClipData(ClipData.newRawUri("", uri));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    final Intent result = mActivity.getCrossProfileResult(intent);
    assertNotNull(result);
    assertEquals(MESSAGE, result.getStringExtra("extra_response"));
}

From source file:com.android.cts.intent.sender.IntentSenderTest.java

/**
 * This method will send an intent to a receiver in another profile.
 * This intent will have, in the ClipData, a uri whose associated file stores a message.
 * The receiver will read the message from the uri, and put it inside the result intent.
 *///from w  w w  .  ja  va2  s  .c om
public void testReceiverCanRead() throws Exception {
    Uri uri = getUriWithTextInFile("reading_test", MESSAGE);
    assertTrue(uri != null);
    Intent intent = new Intent(ACTION_READ_FROM_URI);
    intent.setClipData(ClipData.newRawUri("", uri));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    final Intent result = mActivity.getResult(intent);
    assertNotNull(result);
    assertEquals(MESSAGE, result.getStringExtra("extra_response"));
}

From source file:org.stenerud.kscrash.KSCrashReportFilterEmail.java

@Override
public void filterReports(List reports, CompletionCallback completionCallback)
        throws KSCrashReportFilteringFailedException {
    ArrayList<Uri> attachments = new ArrayList<>();
    String authority = BuildConfig.APPLICATION_ID + ".provider";
    for (Object report : reports) {
        attachments.add(FileProvider.getUriForFile(context, authority, (File) report));
    }//from   w ww  .  j  a  v  a 2  s  .  c o m

    Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setType("*/*");
    // TODO: Why does this fail?
    //        intent.setData(Uri.parse("mailto:"));
    intent.putExtra(Intent.EXTRA_EMAIL, recipients.toArray());
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    // Workaround for framework bug
    ArrayList<String> text = new ArrayList<>();
    text.add(message);
    intent.putExtra(Intent.EXTRA_TEXT, text);
    intent.putExtra(Intent.EXTRA_STREAM, attachments);

    if (intent.resolveActivity(context.getPackageManager()) != null) {
        context.startActivity(intent);
    }

    completionCallback.onCompletion(reports);
}

From source file:org.sufficientlysecure.keychain.ui.dialog.ShareLogDialogFragment.java

@NonNull
@Override//from www  .j  a  v a2  s .c  om
public Dialog onCreateDialog(Bundle savedInstanceState) {

    final Uri stream = getArguments().getParcelable(ARG_STREAM);

    ContextThemeWrapper theme = ThemeChanger.getDialogThemeWrapper(getActivity());

    CustomAlertDialogBuilder builder = new CustomAlertDialogBuilder(theme);
    builder.setTitle(R.string.share_log_dialog_title).setMessage(R.string.share_log_dialog_message)
            .setNegativeButton(R.string.share_log_dialog_cancel_button, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss();
                }
            }).setPositiveButton(R.string.share_log_dialog_share_button, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismiss();
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_STREAM, stream);
                    intent.setType("text/plain");
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    startActivity(intent);
                }
            });

    return builder.show();
}

From source file:com.github.vase4kin.teamcityapp.artifact.router.ArtifactRouterImpl.java

/**
 * {@inheritDoc}//from ww  w .ja va 2 s  .c om
 */
@Override
public void startFileActivity(File file) {
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
    String type = map.getMimeTypeFromExtension(ext);

    if (type == null) {
        type = ALL_FILES_TYPE;
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri data = FileProvider.getUriForFile(mActivity, BuildConfig.APPLICATION_ID + ".provider", file);
    intent.setDataAndType(data, type);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    //User couldn't have app with type intent
    try {
        mActivity.startActivity(intent);
    } catch (android.content.ActivityNotFoundException e) {
        intent.setDataAndType(data, ALL_FILES_TYPE);
        mActivity.startActivity(intent);
    }
}

From source file:com.digitalarx.android.files.FileOperationsHelper.java

public void openFile(OCFile file) {
    if (file != null) {
        String storagePath = file.getStoragePath();
        String encodedStoragePath = WebdavUtils.encodePath(storagePath);

        Intent intentForSavedMimeType = new Intent(Intent.ACTION_VIEW);
        intentForSavedMimeType.setDataAndType(Uri.parse("file://" + encodedStoragePath), file.getMimetype());
        intentForSavedMimeType//from  w  w  w  . j ava 2  s .  co  m
                .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        Intent intentForGuessedMimeType = null;
        if (storagePath.lastIndexOf('.') >= 0) {
            String guessedMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
            if (guessedMimeType != null && !guessedMimeType.equals(file.getMimetype())) {
                intentForGuessedMimeType = new Intent(Intent.ACTION_VIEW);
                intentForGuessedMimeType.setDataAndType(Uri.parse("file://" + encodedStoragePath),
                        guessedMimeType);
                intentForGuessedMimeType.setFlags(
                        Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        }

        Intent chooserIntent = null;
        if (intentForGuessedMimeType != null) {
            chooserIntent = Intent.createChooser(intentForGuessedMimeType,
                    mFileActivity.getString(R.string.actionbar_open_with));
        } else {
            chooserIntent = Intent.createChooser(intentForSavedMimeType,
                    mFileActivity.getString(R.string.actionbar_open_with));
        }

        mFileActivity.startActivity(chooserIntent);

    } else {
        Log_OC.wtf(TAG, "Trying to open a NULL OCFile");
    }
}

From source file:net.bluehack.ui.Components.AvatarUpdater.java

public void openCamera() {
    try {// w w  w. j  a v a 2 s.co m
        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("tmessages", e);
    }
}

From source file:kr.wdream.ui.Components.AvatarUpdater.java

public void openCamera() {
    try {//from   w ww .  j  a  v a2  s .  c o  m
        Log.d("AvatarUpdater", "openCamera");
        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("tmessages", e);
    }
}

From source file:com.commonsware.android.tte.DocumentStorageService.java

private void load(Uri document) {
    try {/*from  ww  w  . j a v a 2s .  co m*/
        boolean weHavePermission = false;
        boolean isContent = ContentResolver.SCHEME_CONTENT.equals(document.getScheme());

        if (isContent) {
            int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

            getContentResolver().takePersistableUriPermission(document, perms);

            for (UriPermission perm : getContentResolver().getPersistedUriPermissions()) {
                if (perm.getUri().equals(document)) {
                    weHavePermission = true;
                }
            }
        } else {
            weHavePermission = true;
        }

        if (weHavePermission) {
            try {
                InputStream is = getContentResolver().openInputStream(document);

                try {
                    String text = slurp(is);
                    DocumentFile docFile;

                    if (isContent) {
                        docFile = DocumentFile.fromSingleUri(this, document);
                    } else {
                        docFile = DocumentFile.fromFile(new File(document.getPath()));
                    }

                    EventBus.getDefault().post(
                            new DocumentLoadedEvent(document, text, docFile.getName(), docFile.canWrite()));
                } finally {
                    is.close();
                }
            } catch (Exception e) {
                Log.e(getClass().getSimpleName(), "Exception loading " + document.toString(), e);
                EventBus.getDefault().post(new DocumentLoadErrorEvent(document, e));
            }
        } else {
            Log.e(getClass().getSimpleName(), "We failed to get permissions for " + document.toString());
            EventBus.getDefault().post(new DocumentPermissionFailureEvent(document));
        }
    } catch (SecurityException e) {
        Log.e(getClass().getSimpleName(), "Exception getting permissions for " + document.toString(), e);
        EventBus.getDefault().post(new DocumentPermissionFailureEvent(document));
    }
}