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.messaging.ui.UIIntentsImpl.java

/**
 * Get an intent which takes you to a conversation
 *///from  w w w.java  2  s.  c  om
private Intent getConversationActivityIntent(final Context context, final String conversationId,
        final MessageData draft, final boolean withCustomTransition) {
    final Intent intent = new Intent(context, ConversationActivity.class);

    // Always try to reuse the same ConversationActivity in the current task so that we don't
    // have two conversation activities in the back stack.
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Otherwise we're starting a new conversation
    if (conversationId != null) {
        intent.putExtra(UI_INTENT_EXTRA_CONVERSATION_ID, conversationId);
    }
    if (draft != null) {
        intent.putExtra(UI_INTENT_EXTRA_DRAFT_DATA, draft);

        // If draft attachments came from an external content provider via a share intent, we
        // need to propagate the URI permissions through to ConversationActivity. This requires
        // putting the URIs into the ClipData (setData also works, but accepts only one URI).
        ClipData clipData = null;
        for (final MessagePartData partData : draft.getParts()) {
            if (partData.isAttachment()) {
                final Uri uri = partData.getContentUri();
                if (clipData == null) {
                    clipData = ClipData.newRawUri("Attachments", uri);
                } else {
                    clipData.addItem(new ClipData.Item(uri));
                }
            }
        }
        if (clipData != null) {
            intent.setClipData(clipData);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    }
    if (withCustomTransition) {
        intent.putExtra(UI_INTENT_EXTRA_WITH_CUSTOM_TRANSITION, true);
    }

    if (!(context instanceof Activity)) {
        // If the caller supplies an application context, and not an activity context, we must
        // include this flag
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    return intent;
}

From source file:com.doplgangr.secrecy.views.FileViewer.java

void sendMultiple(final ArrayList<FilesListFragment.DecryptArgHolder> args) {
    new Thread(new Runnable() {
        @Override//from   w  w w  . j a  v a2s .  c o  m
        public void run() {
            ArrayList<Uri> uris = new ArrayList<Uri>();
            Set<String> mimes = new HashSet<String>();
            MimeTypeMap myMime = MimeTypeMap.getSingleton();
            for (FilesListFragment.DecryptArgHolder arg : args) {
                File tempFile = getFile(arg.encryptedFile, arg.onFinish);
                //File specified is not invalid
                if (tempFile != null) {
                    if (tempFile.getParentFile().equals(Storage.getTempFolder()))
                        tempFile = new java.io.File(Storage.getTempFolder(), tempFile.getName());
                    uris.add(OurFileProvider.getUriForFile(context, OurFileProvider.FILE_PROVIDER_AUTHORITY,
                            tempFile));
                    mimes.add(myMime.getMimeTypeFromExtension(arg.encryptedFile.getType()));

                }
            }
            if (uris.size() == 0 || mimes.size() == 0)
                return;
            Intent newIntent;
            if (uris.size() == 1) {
                newIntent = new Intent(Intent.ACTION_SEND);
                newIntent.putExtra(Intent.EXTRA_STREAM, uris.get(0));
            } else {
                newIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                newIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
            }
            if (mimes.size() > 1)
                newIntent.setType("text/plain"); //Mixed filetypes
            else
                newIntent.setType(new ArrayList<String>(mimes).get(0));
            newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            Intent chooserIntent = generateCustomChooserIntent(newIntent, uris);
            try {
                startActivity(Intent.createChooser(chooserIntent,
                        CustomApp.context.getString(R.string.Dialog__send_file)));
                FilesActivity.onPauseDecision.startActivity();
            } catch (android.content.ActivityNotFoundException e) {
                Util.toast(context, CustomApp.context.getString(R.string.Error__no_activity_view),
                        Toast.LENGTH_LONG);
                FilesActivity.onPauseDecision.finishActivity();
            }
        }
    }).start();
}

From source file:cz.maresmar.sfm.app.SfmApp.java

private void sendFeedback(Context context, String subject) {
    Timber.i("Device %s (%s) on SDK %d", Build.DEVICE, Build.MANUFACTURER, Build.VERSION.SDK_INT);

    File logFile = getLogFile();/*from w  w w .  ja va2s .  com*/
    Uri logUri = FileProvider.getUriForFile(this, "cz.maresmar.sfm.FileProvider", logFile);

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "mmrmartin+dev" + '@' + "gmail.com" });
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "[sfm] " + subject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.feedback_mail_text));
    emailIntent.putExtra(Intent.EXTRA_STREAM, logUri);
    emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(emailIntent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        context.grantUriPermission(packageName, logUri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

    context.startActivity(
            Intent.createChooser(emailIntent, getString(R.string.feedback_choose_email_app_dialog)));
}

From source file:com.android.browser.UploadHandler.java

private Intent createCameraIntent(Uri contentUri) {
    if (contentUri == null)
        throw new IllegalArgumentException();
    mCapturedMedia = contentUri;/*from   w w  w .jav  a 2 s.  c  o m*/
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedMedia);
    intent.setClipData(ClipData.newUri(mController.getActivity().getContentResolver(), FILE_PROVIDER_AUTHORITY,
            mCapturedMedia));
    return intent;
}

From source file:com.luan.thermospy.android.fragments.temperaturelog.TemperatureGraph.java

private Intent createShareIntent() {
    File outputDir = getActivity().getExternalCacheDir(); // context being the Activity pointer
    File outputFile = null;//from  w  ww.  java2  s . co m
    try {
        outputFile = File.createTempFile("export", ".csv", outputDir);

        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(outputFile.getAbsolutePath()));

            for (TemperatureEntry entry : mTemperatureList) {
                writer.write(entry.toCsv() + "\n");
            }
            writer.flush();

        } catch (IOException e) {
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (IOException e) {
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    if (outputFile != null) {
        Uri u1 = Uri.fromFile(outputFile);

        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Temperature log from Thermospy");
        sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
        sendIntent.setType("application/csv");
        sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return sendIntent;
    }
    return null;
}

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

/**
 * Ensure that sender is only able to send data that it has access to.
 *//*from  w  w  w .  ja v  a2  s . c  om*/
public void testSecurity() throws Exception {
    // Pick a URI that neither of us have access to; it doens't matter if
    // its missing, since we expect a SE before a FNFE.
    final Uri uri = Uri.parse("content://media/external/images/media/10240");
    final Intent intent = new Intent(ACTION_READ_FROM_URI);
    intent.setClipData(ClipData.newRawUri("", uri));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    // We're expecting to run into a security exception
    final Intent result = mActivity.getResult(intent);
    if (result == null) {
        // This is fine; probably of a SecurityException when off in the
        // system somewhere.
    } else {
        // But if we somehow came through, make sure they threw.
        assertTrue(result.getBooleanExtra("extra_caught_security_exception", false));
    }
}

From source file:free.rm.skytube.gui.businessobjects.updates.UpgradeAppTask.java

/**
 * Ask the user whether he wants to install the latest SkyTube's APK file.
 *
 * @param apkFile   APK file to install.
 *///from  w  w w. j a  va  2s .com
private void displayUpgradeAppDialog(File apkFile) {
    Uri apkFileURI = (android.os.Build.VERSION.SDK_INT >= 24)
            ? FileProvider.getUriForFile(context,
                    context.getApplicationContext().getPackageName() + ".provider", apkFile) // we now need to call FileProvider.getUriForFile() due to security changes in Android 7.0+
            : Uri.fromFile(apkFile);
    Intent intent = new Intent(Intent.ACTION_VIEW);

    intent.setDataAndType(apkFileURI, "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK /* asks the user to open the newly updated app */
            | Intent.FLAG_GRANT_READ_URI_PERMISSION /* to avoid a crash due to security changes in Android 7.0+ */);
    context.startActivity(intent);
}

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

/**
 * Ensure that sender is only able to send data that it has access to.
 *///from  w w w . j  a v  a 2 s. c o m
public void testSecurity() throws Exception {
    // Pick a URI that neither of us have access to; it doens't matter if
    // its missing, since we expect a SE before a FNFE.
    final Uri uri = Uri.parse("content://media/external/images/media/10240");
    final Intent intent = new Intent(ACTION_READ_FROM_URI);
    intent.setClipData(ClipData.newRawUri("", uri));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    // We're expecting to run into a security exception
    final Intent result = mActivity.getCrossProfileResult(intent);
    if (result == null) {
        // This is fine; probably of a SecurityException when off in the
        // system somewhere.
    } else {
        // But if we somehow came through, make sure they threw.
        assertTrue(result.getBooleanExtra("extra_caught_security_exception", false));
    }
}

From source file:com.google.android.apps.forscience.whistlepunk.PictureUtils.java

public static void launchExternalViewer(Activity activity, String fileUrl) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
    String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    if (!TextUtils.isEmpty(type)) {
        String filePath = fileUrl;
        if (filePath.startsWith("file:")) {
            filePath = filePath.substring("file:".length());
        }//from   ww w. j  a  v a2 s  .c om
        Uri photoUri = FileProvider.getUriForFile(activity, activity.getPackageName(), new File(filePath));
        intent.setDataAndType(photoUri, type);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            // Needed to avoid security exception on KitKat.
            intent.setClipData(ClipData.newRawUri(null, photoUri));
        }
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        try {
            activity.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Log.e(TAG, "No activity found to handle this " + fileUrl + " type " + type);
        }
    } else {
        Log.w(TAG, "Could not find mime type for " + fileUrl);
    }
}

From source file:com.dexin.MainActivity.java

public void startCamera() {
    if (PermissionUtils.requestPermission(this, CAMERA_PERMISSIONS_REQUEST,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri photoUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider",
                getCameraFile());/*from  w w w. j  av a2  s.  c  o  m*/
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, CAMERA_IMAGE_REQUEST);
    }
}