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.HumanDecisionSupportSystemsLaboratory.DD_P2P.Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override/*from  ww w . ja  v a  2s.co  m*/
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (resultCode == RESULT_OK && requestCode == this.RESULT_ADD_PEER) {
        byte[] _pi = resultData.getByteArrayExtra(AddSafe.PI);
        net.ddp2p.common.hds.PeerInput pi = null;
        if (_pi != null)
            try {
                pi = new PeerInput().decode(new Decoder(_pi));
            } catch (Exception e) {
                e.printStackTrace();
            }
        if (pi == null)
            pi = Safe.peerInput;
        new PeerCreatingThread(pi).start();

        super.onActivityResult(requestCode, resultCode, resultData);
        return;
    }
    if (resultCode == RESULT_OK && resultData != null) {
        Uri uri = null;

        if (requestCode == SELECT_PHOTO) {
            uri = resultData.getData();
            Log.i("Uri", "Uri: " + uri.toString());
        } else if (requestCode == SELECT_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);

        selectImageFile = new File(selectedImagePath);
        String error;
        StegoStructure adr[] = DD.getAvailableStegoStructureInstances();
        int[] selected = new int[1];
        try {
            error = DD.loadBMP(selectImageFile, adr, selected);
            Log.i("error", "error: " + error);
            if (error == "") {
                adr[selected[0]].save();
                Toast.makeText(this, "add new safe other successfully!", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Unable to load safe from this photo!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }
    super.onActivityResult(requestCode, resultCode, resultData);
}

From source file:com.maskyn.fileeditorpro.activity.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_FILE_CODE) {

            final Uri data = intent.getData();
            final GreatUri newUri = new GreatUri(data, AccessStorageApi.getPath(this, data),
                    AccessStorageApi.getName(this, data));

            newFileToOpen(newUri, "");
        } else if (requestCode == SELECT_FOLDER_CODE) {
            FileFilter fileFilter = new FileFilter() {
                public boolean accept(File file) {
                    return file.isFile();
                }//from  w  w w  .  jav a  2 s.c o m
            };
            final Uri data = intent.getData();
            File dir = new File(data.getPath());
            File[] fileList = dir.listFiles(fileFilter);
            for (int i = 0; i < fileList.length; i++) {
                Uri particularUri = Uri.parse("file://" + fileList[i].getPath());
                final GreatUri newUri = new GreatUri(particularUri,
                        AccessStorageApi.getPath(this, particularUri),
                        AccessStorageApi.getName(this, particularUri));
                greatUris.add(newUri);

                refreshList(newUri, true, false);
                arrayAdapter.selectPosition(newUri);
            }
            if (fileList.length > 0) {
                Uri particularUri = Uri.parse("file://" + fileList[0].getPath());
                final GreatUri newUri = new GreatUri(particularUri,
                        AccessStorageApi.getPath(this, particularUri),
                        AccessStorageApi.getName(this, particularUri));
                newFileToOpen(newUri, "");
            }

        } else {

            final Uri data = intent.getData();
            final GreatUri newUri = new GreatUri(data, AccessStorageApi.getPath(this, data),
                    AccessStorageApi.getName(this, data));

            // grantUriPermission(getPackageName(), data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            final int takeFlags = intent.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(data, takeFlags);

            if (requestCode == READ_REQUEST_CODE || requestCode == CREATE_REQUEST_CODE) {

                newFileToOpen(newUri, "");
            }

            if (requestCode == SAVE_AS_REQUEST_CODE) {

                new SaveFileTask(this, newUri, pageSystem.getAllText(mEditor.getText().toString()),
                        currentEncoding, new SaveFileTask.SaveFileInterface() {
                            @Override
                            public void fileSaved(Boolean success) {
                                savedAFile(greatUri, false);
                                newFileToOpen(newUri, "");
                            }
                        }).execute();
            }
        }

    }
}

From source file:com.osama.cryptofm.filemanager.ui.FilemanagerTabs.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == GET_PERMISSION_CODE) {
            Uri treeUri = data.getData();
            Log.d(TAG, "onActivityResult: tree uri is: " + treeUri);
            //save the uri for later use
            SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("tree_uri", treeUri.toString());
            editor.apply();/*w w w .j  a  v a  2s.  c  o  m*/
            editor.commit();

            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
    }
}

From source file:org.cm.podd.report.activity.SettingActivity.java

private void captureImageFromCamera() {
    mCurrentPhotoUri = getImageUri();//www. j av  a 2 s .  c o m
    Intent photoTakerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    photoTakerIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 1024 * 1024);
    photoTakerIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    photoTakerIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoUri);
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
        photoTakerIntent
                .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            photoTakerIntent.setClipData(ClipData.newRawUri("", mCurrentPhotoUri));
        }
    }
    startActivityForResult(photoTakerIntent, REQ_CODE_TAKE_IMAGE);
}

From source file:com.android.nfc.beam.BeamTransferManager.java

Intent buildViewIntent() {
    if (mPaths.size() == 0)
        return null;

    Intent viewIntent = new Intent(Intent.ACTION_VIEW);

    String filePath = mPaths.get(0);
    Uri mediaUri = mMediaUris.get(filePath);
    Uri uri = mediaUri != null ? mediaUri
            : FileProvider.getUriForFile(mContext, "com.google.android.nfc.fileprovider", new File(filePath));
    viewIntent.setDataAndTypeAndNormalize(uri, mMimeTypes.get(filePath));
    viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
            | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    return viewIntent;
}

From source file:cz.maresmar.sfm.service.plugin.sync.SyncHandler.java

private void startPlugin(@NonNull String plugin, long portalId, long credentialsID, @SyncTask int pluginTasks) {
    Intent intent = PluginUtils.buildPluginIntent(plugin);

    // Puts action details
    intent.setAction(ActionContract.ACTION_SYNC);
    intent.putExtra(ActionContract.EXTRA_PORTAL_ID, portalId);
    intent.putExtra(ActionContract.EXTRA_CREDENTIAL_ID, credentialsID);
    intent.putExtra(ActionContract.EXTRA_TASKS, pluginTasks);

    // Provides access to login data
    intent.setData(LogData.getUri(portalId, credentialsID));

    // Give permissions to access data
    int rwFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

    String packageName = intent.getComponent().getPackageName();
    mContext.grantUriPermission(packageName, intent.getData(), rwFlags);
    mContext.grantUriPermission(packageName, ProviderContract.Action.getCredentialUri(credentialsID), rwFlags);
    mContext.grantUriPermission(packageName, ProviderContract.GroupMenuEntry.getPortalUri(portalId), rwFlags);
    mContext.grantUriPermission(packageName, ProviderContract.MenuEntry.getPortalUri(portalId), rwFlags);

    Timber.i("Starting plugin \"%s\" on portal %d with credential %d", plugin, portalId, credentialsID);
    // Fire start
    PluginUtils.startPlugin(mContext, intent);
}

From source file:com.owncloud.android.ui.preview.PreviewMediaFragment.java

/**
 * Opens the previewed file with an external application.
 * //  w w w.  ja  v a 2s. c  o  m
 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server, 
 * we should get a list of available apps for MIME tpye in the server and join it with the list of 
 * available apps for the MIME type known from the file extension, to let the user choose
 */
private void openFile() {
    stopPreview(true);
    String storagePath = mFile.getStoragePath();
    String encodedStoragePath = WebdavUtils.encodePath(storagePath);
    try {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mFile.getMimetype());
        i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivity(i);

    } catch (Throwable t) {
        Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: "
                + mFile.getMimetype());
        boolean toastIt = true;
        String mimeType = "";
        try {
            Intent i = new Intent(Intent.ACTION_VIEW);
            mimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
            if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
                if (mimeType != null) {
                    i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mimeType);
                } else {
                    // desperate try
                    i.setDataAndType(Uri.parse("file://" + encodedStoragePath), "*-/*");
                }
                i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivity(i);
                toastIt = false;
            }

        } catch (IndexOutOfBoundsException e) {
            Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);

        } catch (ActivityNotFoundException e) {
            Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType
                    + " obtained from extension");

        } catch (Throwable th) {
            Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);

        } finally {
            if (toastIt) {
                Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(),
                        Toast.LENGTH_SHORT).show();
            }
        }

    }
    finish();
}

From source file:ml.puredark.hviewer.ui.fragments.SettingFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == RESULT_CHOOSE_DIRECTORY) {
            Uri uriTree = data.getData();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                try {
                    getActivity().getContentResolver().takePersistableUriPermission(uriTree,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                } catch (SecurityException e) {
                    e.printStackTrace();
                }//  w  w  w  .  j  av a  2  s  . com
            }
            String path = uriTree.toString();
            String displayPath = Uri.decode(path);
            SharedPreferencesUtil.saveData(getActivity(), KEY_PREF_DOWNLOAD_PATH, path);
            getPreferenceManager().findPreference(KEY_PREF_DOWNLOAD_PATH).setSummary(displayPath);
        }
    }
}

From source file:net.sf.xfd.provider.PublicProvider.java

@Override
public Uri canonicalize(@NonNull Uri uri) {
    try {/*w  w  w .  ja va  2 s  . c  om*/
        base.assertAbsolute(uri);

        String grantMode = uri.getQueryParameter(URI_ARG_MODE);
        if (TextUtils.isEmpty(grantMode)) {
            grantMode = "r";
        }

        verifyMac(uri, grantMode, grantMode);

        final int flags = ParcelFileDescriptor.parseMode(grantMode);

        final Context context = getContext();
        assert context != null;

        final String packageName = context.getPackageName();

        final Uri canon = DocumentsContract.buildDocumentUri(packageName + FileProvider.AUTHORITY_SUFFIX,
                canonString(uri.getPath()));

        final int callerUid = Binder.getCallingUid();

        if (callerUid != Process.myUid()) {
            int grantFlags = Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;

            if ((flags & ParcelFileDescriptor.MODE_READ_ONLY) == flags) {
                grantFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION;
            } else if ((flags & ParcelFileDescriptor.MODE_WRITE_ONLY) == flags)
                grantFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
            else {
                grantFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
                grantFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION;
            }

            final String[] packages;

            final String caller = getCallingPackage();
            if (caller != null) {
                packages = new String[] { caller };
            } else {
                final PackageManager pm = context.getPackageManager();
                packages = pm.getPackagesForUid(callerUid);
            }

            if (packages != null) {
                for (String pkg : packages) {
                    context.grantUriPermission(pkg, canon, grantFlags);
                }
            }
        }

        return canon;
    } catch (FileNotFoundException e) {
        return null;
    }
}