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.mb.android.MainActivity.java

@android.webkit.JavascriptInterface
@org.xwalk.core.JavascriptInterface//  ww w .  j  av  a 2  s.  c o  m
public void chooseDirectory() {

    getLogger().Info("begin chooseDirectory");

    if (!authorizeStorage(ExternalStoragePermissionRequestCode)) {
        return;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivityForResult(intent, REQUEST_DIRECTORY_SAF);
    } else {

        getLogger().Info("creating intent for FilePickerActivity");
        Intent intent = new Intent(this, FilePickerActivity.class);
        // This works if you defined the intent filter
        // Intent i = new Intent(Intent.ACTION_GET_CONTENT);

        // Set these depending on your use case. These are the defaults.
        intent.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
        intent.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, true);
        intent.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_DIR);

        // Configure initial directory by specifying a String.
        // You could specify a String like "/storage/emulated/0/", but that can
        // dangerous. Always use Android's API calls to get paths to the SD-card or
        // internal memory.
        intent.putExtra(FilePickerActivity.EXTRA_START_PATH,
                Environment.getExternalStorageDirectory().getPath());

        getLogger().Info("startActivityForResult for FilePickerActivity");
        startActivityForResult(intent, REQUEST_DIRECTORY);
    }
}

From source file:com.apptentive.android.sdk.module.messagecenter.view.MessageCenterActivityContent.java

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case Constants.REQUEST_CODE_PHOTO_FROM_SYSTEM_PICKER: {
            if (data == null) {
                Log.d("no image is picked");
                return;
            }//from w w  w. j  ava2s .  c  o m
            imagePickerLaunched = false;
            Uri uri;
            //Android SDK less than 19
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                uri = data.getData();
            } else {
                //for Android 4.4
                uri = data.getData();
                int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
                viewActivity.getContentResolver().takePersistableUriPermission(uri, takeFlags);
            }

            String originalPath = Util.getRealFilePathFromUri(viewActivity, uri);
            if (originalPath != null) {
                /* If able to retrieve file path and creation time from uri, cache file name will be generated
                 * from the md5 of file path + creation time
                 */
                long creation_time = Util.getContentCreationTime(viewActivity, uri);
                Uri fileUri = Uri.fromFile(new File(originalPath));
                File cacheDir = Util.getDiskCacheDir(viewActivity);
                addAttachmentsToComposer(Arrays.asList(new ImageItem(originalPath,
                        Util.generateCacheFileFullPath(fileUri, cacheDir, creation_time),
                        Util.getMimeTypeFromUri(viewActivity, uri), creation_time)));
            } else {
                /* If not able to get image file path due to not having READ_EXTERNAL_STORAGE permission,
                 * cache name will be generated from md5 of uri string
                 */
                File cacheDir = Util.getDiskCacheDir(viewActivity);
                String cachedFileName = Util.generateCacheFileFullPath(uri, cacheDir, 0);
                addAttachmentsToComposer(Arrays.asList(new ImageItem(uri.toString(), cachedFileName,
                        Util.getMimeTypeFromUri(viewActivity, uri), 0)));
            }

            break;
        }
        default:
            break;
        }
    }
}

From source file:com.HumanDecisionSupportSystemsLaboratory.DD_P2P.OrgProfile.java

@SuppressLint("NewApi")
@Override//  w  w  w  . j  a v a  2 s .  co  m
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (resultCode == RESULT_OK && resultData != null) {
        Uri uri = null;

        if (requestCode == SELECT_PROFILE_PHOTO) {
            uri = resultData.getData();
            Log.i("Uri", "Uri: " + uri.toString());
        } else if (requestCode == SELECT_PPROFILE_PHOTO_KITKAT) {
            uri = resultData.getData();
            Log.i("Uri_kitkat", "Uri: " + uri.toString());
            final int takeFlags = resultData.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(uri, takeFlags);
        }

        selectedImagePath = FileUtils.getPath(this, uri);
        Log.i("path", "path: " + selectedImagePath);

        Bitmap bmp = BitmapFactory.decodeFile(selectedImagePath);
        // String strFromBmp = PhotoUtil.BitmapToString(bmp);
        byte[] icon = PhotoUtil.BitmapToByteArray(bmp, 100);
        Log.i(TAG, Util.stringSignatureFromByte(icon));

        byteIcon = icon;
        Log.d(TAG, "selected constituent pic: " + byteIcon.length);
        setProfilePhoto.setImageBitmap(bmp);

    }
}

From source file:com.ereinecke.eatsafe.MainActivity.java

private void launchPhotoIntent(int whichPhoto) {

    Logd(LOG_TAG, "Launching intent for photo #" + whichPhoto);
    // create Intent to take a picture and return control to the calling application
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

        // Create the File where the photo should go
        File photoFile = openOutputMediaFile();
        Logd(LOG_TAG, "photoReceived: " + photoReceived);

        if (photoFile != null) {

            Uri photoUri = StreamProvider.getUriForFile("com.ereinecke.eatsafe.fileprovider", photoFile);
            try {
                Logd(LOG_TAG, "photoUri: " + photoUri.toString());
            } catch (Exception e) {
                Logd(LOG_TAG, "photoUri is null: " + e.getMessage());
            }/*from w  ww . ja  v  a2 s . com*/
            // set the image file name
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            takePictureIntent.putExtra(Constants.WHICH_PHOTO, whichPhoto);
            takePictureIntent
                    .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            // start the image capture Intent
            startActivityForResult(takePictureIntent, Constants.CAMERA_IMAGE_REQUEST);
        }
    }
}

From source file:it.feio.android.omninotes.DetailFragment.java

private void initViewAttachments() {

    // Attachments position based on preferences
    if (prefs.getBoolean(Constants.PREF_ATTANCHEMENTS_ON_BOTTOM, false)) {
        attachmentsBelow.inflate();/*w ww .j a  v a2  s .  com*/
    } else {
        attachmentsAbove.inflate();
    }
    mGridView = (ExpandableHeightGridView) root.findViewById(R.id.gridview);

    // Some fields can be filled by third party application and are always shown
    mAttachmentAdapter = new AttachmentAdapter(mainActivity, noteTmp.getAttachmentsList(), mGridView);

    // Initialzation of gridview for images
    mGridView.setAdapter(mAttachmentAdapter);
    mGridView.autoresize();

    // Click events for images in gridview (zooms image)
    mGridView.setOnItemClickListener((parent, v, position, id) -> {
        Attachment attachment = (Attachment) parent.getAdapter().getItem(position);
        Uri uri = attachment.getUri();
        Intent attachmentIntent;
        if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) {

            attachmentIntent = new Intent(Intent.ACTION_VIEW);
            attachmentIntent.setDataAndType(uri, StorageHelper.getMimeType(mainActivity, attachment.getUri()));
            attachmentIntent
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (IntentChecker.isAvailable(mainActivity.getApplicationContext(), attachmentIntent, null)) {
                startActivity(attachmentIntent);
            } else {
                mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN);
            }

            // Media files will be opened in internal gallery
        } else if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) {
            // Title
            noteTmp.setTitle(getNoteTitle());
            noteTmp.setContent(getNoteContent());
            String title1 = TextHelper.parseTitleAndContent(mainActivity, noteTmp)[0].toString();
            // Images
            int clickedImage = 0;
            ArrayList<Attachment> images = new ArrayList<>();
            for (Attachment mAttachment : noteTmp.getAttachmentsList()) {
                if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
                    images.add(mAttachment);
                    if (mAttachment.equals(attachment)) {
                        clickedImage = images.size() - 1;
                    }
                }
            }
            // Intent
            attachmentIntent = new Intent(mainActivity, GalleryActivity.class);
            attachmentIntent.putExtra(Constants.GALLERY_TITLE, title1);
            attachmentIntent.putParcelableArrayListExtra(Constants.GALLERY_IMAGES, images);
            attachmentIntent.putExtra(Constants.GALLERY_CLICKED_IMAGE, clickedImage);
            startActivity(attachmentIntent);

        } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) {
            playback(v, attachment.getUri());
        }

    });

    mGridView.setOnItemLongClickListener((parent, v, position, id) -> {

        // To avoid deleting audio attachment during playback
        if (mPlayer != null)
            return false;

        List<String> items = Arrays.asList(getResources().getStringArray(R.array.attachments_actions));
        if (!Constants.MIME_TYPE_SKETCH.equals(mAttachmentAdapter.getItem(position).getMime_type())) {
            items = items.subList(0, items.size() - 1);
        }

        new MaterialDialog.Builder(mainActivity).title(mAttachmentAdapter.getItem(position).getName())
                .items(items.toArray(new String[items.size()]))
                .itemsCallback((materialDialog, view, i, charSequence) -> performAttachmentAction(position, i))
                .build().show();
        return true;
    });
}

From source file:com.almalence.opencam.Fragment.java

@TargetApi(19)
@Override/* w  w  w .j  a  v  a 2s  . c  om*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CHOOSE_FOLDER_CODE) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.instance);
        if (resultCode == Activity.RESULT_OK) {
            Uri treeUri = data.getData();

            getActivity().getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            prefs.edit().putString(ApplicationScreen.sSavePathPref, treeUri.toString()).commit();
        } else {
            prefs.edit().putString(ApplicationScreen.sSaveToPref, "0").commit();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

From source file:com.dycody.android.idealnote.DetailFragment.java

private void initViewAttachments() {

    // Attachments position based on preferences
    if (prefs.getBoolean(Constants.PREF_ATTANCHEMENTS_ON_BOTTOM, false)) {
        attachmentsBelow.inflate();/*  ww w  .j  av a2 s .  co m*/
    } else {
        attachmentsAbove.inflate();
    }
    mGridView = (ExpandableHeightGridView) root.findViewById(R.id.gridview);

    // Some fields can be filled by third party application and are always shown
    mAttachmentAdapter = new AttachmentAdapter(mainActivity, noteTmp.getAttachmentsList(), mGridView);

    // Initialzation of gridview for images
    mGridView.setAdapter(mAttachmentAdapter);
    mGridView.autoresize();

    // Click events for images in gridview (zooms image)
    mGridView.setOnItemClickListener((parent, v, position, id) -> {
        Attachment attachment = (Attachment) parent.getAdapter().getItem(position);
        Uri uri = attachment.getUri();
        Intent attachmentIntent;
        if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) {

            attachmentIntent = new Intent(Intent.ACTION_VIEW);
            attachmentIntent.setDataAndType(uri, StorageHelper.getMimeType(mainActivity, attachment.getUri()));
            attachmentIntent
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (IntentChecker.isAvailable(mainActivity.getApplicationContext(), attachmentIntent, null)) {
                startActivity(attachmentIntent);
            } else {
                Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, Toast.LENGTH_SHORT)
                        .show();
                //mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN);
            }

            // Media files will be opened in internal gallery
        } else if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())
                || Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) {
            // Title
            noteTmp.setTitle(getNoteTitle());
            noteTmp.setContent(getNoteContent());
            String title1 = TextHelper.parseTitleAndContent(mainActivity, noteTmp)[0].toString();
            // Images
            int clickedImage = 0;
            ArrayList<Attachment> images = new ArrayList<>();
            for (Attachment mAttachment : noteTmp.getAttachmentsList()) {
                if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type())
                        || Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
                    images.add(mAttachment);
                    if (mAttachment.equals(attachment)) {
                        clickedImage = images.size() - 1;
                    }
                }
            }
            // Intent
            attachmentIntent = new Intent(mainActivity, GalleryActivity.class);
            attachmentIntent.putExtra(Constants.GALLERY_TITLE, title1);
            attachmentIntent.putParcelableArrayListExtra(Constants.GALLERY_IMAGES, images);
            attachmentIntent.putExtra(Constants.GALLERY_CLICKED_IMAGE, clickedImage);
            startActivity(attachmentIntent);

        } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) {
            playback(v, attachment.getUri());
        }

    });

    mGridView.setOnItemLongClickListener((parent, v, position, id) -> {
        // To avoid deleting audio attachment during playback
        if (mPlayer != null)
            return false;
        List<String> items = Arrays.asList(getResources().getStringArray(R.array.attachments_actions));
        if (!Constants.MIME_TYPE_SKETCH.equals(mAttachmentAdapter.getItem(position).getMime_type())) {
            items = items.subList(0, items.size() - 1);
        }
        Attachment attachment = mAttachmentAdapter.getItem(position);
        new MaterialDialog.Builder(mainActivity)
                .title(attachment.getName() + " (" + AttachmentsHelper.getSize(attachment) + ")")
                .items(items.toArray(new String[items.size()]))
                .itemsCallback((materialDialog, view, i, charSequence) -> performAttachmentAction(position, i))
                .build().show();
        return true;
    });
}

From source file:org.glucosio.android.activity.MainActivity.java

public void showShareDialog(Uri uri) {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setData(uri);//ww w.  j a  v a  2s  .c om
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    shareIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    shareIntent.setType("*/*");
    startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share_using)));
}

From source file:net.gsantner.opoc.util.ShareUtil.java

/**
 * Request edit of image (by image editor/viewer - for example to crop image)
 *
 * @param file File that should be edited
 *//*from   w  ww.j a va 2  s .  co m*/
public void requestPictureEdit(File file) {
    Uri uri = getUriByFileProviderAuthority(file);
    int flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION;

    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setDataAndType(uri, "image/*");
    intent.addFlags(flags);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    intent.putExtra(EXTRA_FILEPATH, file.getAbsolutePath());

    for (ResolveInfo resolveInfo : _context.getPackageManager().queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY)) {
        String packageName = resolveInfo.activityInfo.packageName;
        _context.grantUriPermission(packageName, uri, flags);
    }
    _context.startActivity(Intent.createChooser(intent, null));
}

From source file:de.cachebox_test.splash.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override/*w ww  . j  a  v  a2s  .  co m*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK && requestCode == Global.REQUEST_CODE_GET_WRITE_PERMISSION_ANDROID_5) {
        Uri treeUri = data.getData();

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        final int takeFlags = intent.getFlags()
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        // Check for the freshest data.

        // Uri workPathUri = Uri.parse(workPath);

        ContentResolver cr = getContentResolver();

        grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        cr.takePersistableUriPermission(treeUri, takeFlags);

        List<UriPermission> permissionlist = cr.getPersistedUriPermissions();

        LolipopworkPath = "content://com.android.externalstorage.documents/tree/B8C5-760B%3A";// treeUri.getPath();

        Thread th = new Thread(new Runnable() {

            @Override
            public void run() {
                Initial(width, height);
            }
        });
        th.start();

    }

    if (resultCode == RESULT_OK
            && requestCode == Global.REQUEST_CODE_PICK_FILE_OR_DIRECTORY_FROM_PLATFORM_CONECTOR) {
        if (resultCode == android.app.Activity.RESULT_OK && data != null) {
            // obtain the filename
            Uri fileUri = data.getData();
            if (fileUri != null) {
                String filePath = fileUri.getPath();
                if (filePath != null) {
                    if (getFolderReturnListener != null)
                        getFolderReturnListener.getFolderReturn(filePath);
                }
            }
        }
        return;

    }

}