Example usage for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION

List of usage examples for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION

Introduction

In this page you can find the example usage for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION.

Prototype

int FLAG_GRANT_WRITE_URI_PERMISSION

To view the source code for android.content Intent FLAG_GRANT_WRITE_URI_PERMISSION.

Click Source Link

Document

If set, the recipient of this Intent will be granted permission to perform write operations on the URI in the Intent's data and any URIs specified in its ClipData.

Usage

From source file:com.owncloud.android.ui.helpers.FileOperationsHelper.java

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

        Intent intentForSavedMimeType = new Intent(Intent.ACTION_VIEW);
        intentForSavedMimeType.setDataAndType(file.getExposedFileUri(mFileActivity), file.getMimetype());

        intentForSavedMimeType//from w  w  w. j a  v  a  2s . com
                .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(file.getExposedFileUri(mFileActivity), guessedMimeType);
                intentForGuessedMimeType.setFlags(
                        Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        }

        Intent openFileWithIntent;
        if (intentForGuessedMimeType != null) {
            openFileWithIntent = intentForGuessedMimeType;
        } else {
            openFileWithIntent = intentForSavedMimeType;
        }

        List<ResolveInfo> launchables = mFileActivity.getPackageManager()
                .queryIntentActivities(openFileWithIntent, PackageManager.GET_INTENT_FILTERS);

        if (launchables != null && launchables.size() > 0) {
            try {
                mFileActivity.startActivity(Intent.createChooser(openFileWithIntent,
                        mFileActivity.getString(R.string.actionbar_open_with)));
            } catch (ActivityNotFoundException anfe) {
                mFileActivity
                        .showSnackMessage(mFileActivity.getString(R.string.file_list_no_app_for_file_type));
            }
        } else {
            mFileActivity.showSnackMessage(mFileActivity.getString(R.string.file_list_no_app_for_file_type));
        }

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

From source file:com.example.android.scopeddirectoryaccess.ScopedDirectoryAccessFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == OPEN_DIRECTORY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        getActivity().getContentResolver().takePersistableUriPermission(data.getData(),
                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        updateDirectoryEntries(data.getData());
    }/*www.j  a  v  a2 s . c o  m*/
}

From source file:com.cerema.cloud2.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/*w  w w . ja va 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 openFileWithIntent;
        if (intentForGuessedMimeType != null) {
            openFileWithIntent = intentForGuessedMimeType;
        } else {
            openFileWithIntent = intentForSavedMimeType;
        }

        List<ResolveInfo> launchables = mFileActivity.getPackageManager()
                .queryIntentActivities(openFileWithIntent, PackageManager.GET_INTENT_FILTERS);

        if (launchables != null && launchables.size() > 0) {
            try {
                mFileActivity.startActivity(Intent.createChooser(openFileWithIntent,
                        mFileActivity.getString(R.string.actionbar_open_with)));
            } catch (ActivityNotFoundException anfe) {
                showNoAppForFileTypeToast(mFileActivity.getApplicationContext());
            }
        } else {
            showNoAppForFileTypeToast(mFileActivity.getApplicationContext());
        }

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

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

public void showAlert(final boolean fromTheme) {
    AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
    CharSequence[] items;/* ww w.  j  a v  a 2s. c  o m*/
    if (fromTheme) {
        items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera),
                LocaleController.getString("FromGalley", R.string.FromGalley),
                LocaleController.getString("SelectColor", R.string.SelectColor),
                LocaleController.getString("Default", R.string.Default),
                LocaleController.getString("Cancel", R.string.Cancel) };
    } else {
        items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera),
                LocaleController.getString("FromGalley", R.string.FromGalley),
                LocaleController.getString("Cancel", R.string.Cancel) };
    }
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            try {
                if (i == 0) {
                    try {
                        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(
                                        parentActivity, 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();
                        }
                        parentActivity.startActivityForResult(takePictureIntent, 10);
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                } else if (i == 1) {
                    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                    photoPickerIntent.setType("image/*");
                    parentActivity.startActivityForResult(photoPickerIntent, 11);
                } else if (fromTheme) {
                    if (i == 2) {
                        delegate.needOpenColorPicker();
                    } else if (i == 3) {
                        delegate.didSelectWallpaper(null, null);
                    }
                }
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
    });
    builder.show();
}

From source file:org.glucosio.android.tools.ReadingToCSV.java

public Uri createCSV(final ArrayList<GlucoseReading> readings, String um) {

    File file = new File(context.getFilesDir().getAbsolutePath(), "glucosio_exported_data.csv"); //Getting a file within the dir.

    try {//from  w ww  .  j av  a2s  . c o m
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream);

        osw.append(context.getResources().getString(R.string.dialog_add_concentration));
        osw.append(',');

        osw.append(context.getResources().getString(R.string.dialog_add_measured));
        osw.append(',');

        osw.append(context.getResources().getString(R.string.dialog_add_date));
        osw.append(',');

        osw.append(context.getResources().getString(R.string.dialog_add_time));
        osw.append('\n');

        FormatDateTime dateTool = new FormatDateTime(context);

        if ("mg/dL".equals(um)) {
            for (int i = 0; i < readings.size(); i++) {

                osw.append(readings.get(i).getReading() + "mg/dL");
                osw.append(',');

                osw.append(readings.get(i).getReading_type() + "");
                osw.append(',');

                osw.append(dateTool.convertRawDate(readings.get(i).getCreated() + ""));
                osw.append(',');

                osw.append(dateTool.convertRawTime(readings.get(i).getCreated() + ""));
                osw.append('\n');
            }
        } else {
            GlucosioConverter converter = new GlucosioConverter();

            for (int i = 0; i < readings.size(); i++) {

                osw.append(converter.glucoseToMmolL(readings.get(i).getReading()) + "mmol/L");
                osw.append(',');

                osw.append(dateTool.convertRawDate(readings.get(i).getCreated() + ""));
                osw.append(',');

                osw.append(dateTool.convertRawTime(readings.get(i).getCreated() + ""));
                osw.append('\n');
            }
        }

        osw.flush();
        osw.close();
        Log.i("Glucosio", "Done exporting readings");

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

    context.grantUriPermission(context.getPackageName(), Uri.parse(file.getAbsolutePath()),
            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

    return FileProvider.getUriForFile(context, context.getPackageName() + ".provider.fileprovider",
            file.getAbsoluteFile());
}

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 a message in an extra, and a uri specified by the ClipData.
 * The receiver will read the message from the extra, and write it to the uri in
 * the ClipData./*from  ww w.  j av a2  s  .c  o  m*/
 */
public void testReceiverCanWrite() throws Exception {
    // It's the receiver of the intent that should write to the uri, not us. So, for now, we
    // write an empty string.
    Uri uri = getUriWithTextInFile("writing_test", "");
    assertTrue(uri != null);
    Intent intent = new Intent(ACTION_WRITE_TO_URI);
    intent.setClipData(ClipData.newRawUri("", uri));
    intent.putExtra("extra_message", MESSAGE);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

    mActivity.getResult(intent);
    assertEquals(MESSAGE, getFirstLineFromUri(uri));
}

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 a message in an extra, and a uri specified by the ClipData.
 * The receiver will read the message from the extra, and write it to the uri in
 * the ClipData./*  w w w.  j  a  v  a2s.co m*/
 */
public void testReceiverCanWrite() throws Exception {
    // It's the receiver of the intent that should write to the uri, not us. So, for now, we
    // write an empty string.
    Uri uri = getUriWithTextInFile("writing_test", "");
    assertTrue(uri != null);
    Intent intent = new Intent(ACTION_WRITE_TO_URI);
    intent.setClipData(ClipData.newRawUri("", uri));
    intent.putExtra("extra_message", MESSAGE);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

    mActivity.getCrossProfileResult(intent);
    assertEquals(MESSAGE, getFirstLineFromUri(uri));
}

From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java

/**
 * Get an Intent to capture a photo./*from   ww  w  .  j  av a  2 s . c om*/
 *
 * @return Image capture Intent
 */
@Nullable
public static Intent getTakePhotoIntent(@NonNull Context context) {
    try {
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        final Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider",
                getOutputMediaFile());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            intent.setClipData(ClipData.newUri(context.getContentResolver(), null, uri));
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            final List<ResolveInfo> activities = context.getPackageManager().queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo activity : activities) {
                final String name = activity.activityInfo.packageName;
                context.grantUriPermission(name, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        }

        return intent;
    } catch (IOException e) {
        Log.e(TAG, "Failed to create new file", e);
    }
    return null;
}

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

private static String capturePictureLabel(Context context, IStartable startable) {
    // Starts a picture intent.
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
        File photoFile = null;//from  w  w  w  . j  a  v  a2  s . c o  m
        try {
            photoFile = PictureUtils.createImageFile(
                    AppSingleton.getInstance(context).getSensorEnvironment().getDefaultClock().getNow());
        } catch (IOException ex) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, ex.getMessage());
            }
        }
        if (photoFile != null) {
            Uri photoUri = FileProvider.getUriForFile(context, context.getPackageName(), photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                // Needed to avoid security exception on KitKat.
                takePictureIntent.setClipData(ClipData.newRawUri(null, photoUri));
            }
            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            String pictureLabelPath = "file:" + photoFile.getAbsoluteFile();
            startable.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            return pictureLabelPath;
        }
    }
    return null;
}

From source file:com.android.contacts.util.ContactPhotoUtils.java

/**
 * Adds common extras to gallery intents.
 *
 * @param intent The intent to add extras to.
 * @param photoUri The uri of the file to save the image to.
 *///ww  w  . ja  v  a 2s .c o  m
public static void addPhotoPickerExtras(Intent intent, Uri photoUri) {
    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setClipData(ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, photoUri));
}