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.just.agentweb.AgentWebUtils.java

static void setIntentData(Context context, Intent intent, File file, boolean writeAble) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        intent.setData(getUriFromFile(context, file));
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        if (writeAble) {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }//from   w  w  w .j  a v a  2s .c  o  m
    } else {
        intent.setData(Uri.fromFile(file));
    }
}

From source file:com.keepassdroid.fileselect.FileSelectActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    fileHistory = App.getFileHistory();/*from  ww  w. ja v a  2 s.  c  om*/

    if (fileHistory.hasRecentFiles()) {
        recentMode = true;
        setContentView(R.layout.file_selection);
    } else {
        setContentView(R.layout.file_selection_no_recent);
    }

    mList = (ListView) findViewById(R.id.file_list);

    mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            onListItemClick((ListView) parent, v, position, id);
        }
    });

    // Open button
    Button openButton = (Button) findViewById(R.id.open);
    openButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            String fileName = Util.getEditText(FileSelectActivity.this, R.id.file_filename);

            try {
                PasswordActivity.Launch(FileSelectActivity.this, fileName);
            } catch (ContentFileNotFoundException e) {
                Toast.makeText(FileSelectActivity.this, R.string.file_not_found_content, Toast.LENGTH_LONG)
                        .show();
            } catch (FileNotFoundException e) {
                Toast.makeText(FileSelectActivity.this, R.string.FileNotFound, Toast.LENGTH_LONG).show();
            }

        }
    });

    // Create button
    Button createButton = (Button) findViewById(R.id.create);
    createButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            String filename = Util.getEditText(FileSelectActivity.this, R.id.file_filename);

            // Make sure file name exists
            if (filename.length() == 0) {
                Toast.makeText(FileSelectActivity.this, R.string.error_filename_required, Toast.LENGTH_LONG)
                        .show();
                return;
            }

            // Try to create the file
            File file = new File(filename);
            try {
                if (file.exists()) {
                    Toast.makeText(FileSelectActivity.this, R.string.error_database_exists, Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                File parent = file.getParentFile();

                if (parent == null || (parent.exists() && !parent.isDirectory())) {
                    Toast.makeText(FileSelectActivity.this, R.string.error_invalid_path, Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                if (!parent.exists()) {
                    // Create parent dircetory
                    if (!parent.mkdirs()) {
                        Toast.makeText(FileSelectActivity.this, R.string.error_could_not_create_parent,
                                Toast.LENGTH_LONG).show();
                        return;

                    }
                }

                file.createNewFile();
            } catch (IOException e) {
                Toast.makeText(FileSelectActivity.this,
                        getText(R.string.error_file_not_create) + " " + e.getLocalizedMessage(),
                        Toast.LENGTH_LONG).show();
                return;
            }

            // Prep an object to collect a password once the database has
            // been created
            CollectPassword password = new CollectPassword(new LaunchGroupActivity(filename));

            // Create the new database
            CreateDB create = new CreateDB(FileSelectActivity.this, filename, password, true);
            ProgressTask createTask = new ProgressTask(FileSelectActivity.this, create,
                    R.string.progress_create);
            createTask.run();

        }

    });

    ImageButton browseButton = (ImageButton) findViewById(R.id.browse_button);
    browseButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (StorageAF.useStorageFramework(FileSelectActivity.this)) {
                Intent i = new Intent(StorageAF.ACTION_OPEN_DOCUMENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
                startActivityForResult(i, OPEN_DOC);
            } else {
                Intent i;
                i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");

                try {
                    startActivityForResult(i, GET_CONTENT);
                } catch (ActivityNotFoundException e) {
                    lookForOpenIntentsFilePicker();
                } catch (SecurityException e) {
                    lookForOpenIntentsFilePicker();
                }
            }
        }

        private void lookForOpenIntentsFilePicker() {

            if (Interaction.isIntentAvailable(FileSelectActivity.this, Intents.OPEN_INTENTS_FILE_BROWSE)) {
                Intent i = new Intent(Intents.OPEN_INTENTS_FILE_BROWSE);
                i.setData(Uri.parse("file://" + Util.getEditText(FileSelectActivity.this, R.id.file_filename)));
                try {
                    startActivityForResult(i, FILE_BROWSE);
                } catch (ActivityNotFoundException e) {
                    showBrowserDialog();
                }

            } else {
                showBrowserDialog();
            }
        }

        private void showBrowserDialog() {
            BrowserDialog diag = new BrowserDialog(FileSelectActivity.this);
            diag.show();
        }
    });

    fillData();

    registerForContextMenu(mList);

    // Load default database
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String fileName = prefs.getString(PasswordActivity.KEY_DEFAULT_FILENAME, "");

    if (fileName.length() > 0) {
        Uri dbUri = UriUtil.parseDefaultFile(fileName);
        String scheme = dbUri.getScheme();

        if (!EmptyUtils.isNullOrEmpty(scheme) && scheme.equalsIgnoreCase("file")) {
            String path = dbUri.getPath();
            File db = new File(path);

            if (db.exists()) {
                try {
                    PasswordActivity.Launch(FileSelectActivity.this, path);
                } catch (Exception e) {
                    // Ignore exception
                }
            }
        } else {
            try {
                PasswordActivity.Launch(FileSelectActivity.this, dbUri.toString());
            } catch (Exception e) {
                // Ignore exception
            }
        }
    }
}

From source file:com.android.gallery3d.gadget.WidgetConfigure.java

private void setChoosenPhoto(final Intent data) {
    AsyncTask.execute(new Runnable() {
        @Override// w  ww. ja  va  2 s.  c  om
        public void run() {
            Resources res = getResources();

            float width = res.getDimension(R.dimen.appwidget_width);
            float height = res.getDimension(R.dimen.appwidget_height);

            // We try to crop a larger image (by scale factor), but there is still
            // a bound on the binder limit.
            float scale = Math.min(WIDGET_SCALE_FACTOR, MAX_WIDGET_SIDE / Math.max(width, height));

            int widgetWidth = Math.round(width * scale);
            int widgetHeight = Math.round(height * scale);

            File cropSrc = new File(getCacheDir(), "crop_source.png");
            File cropDst = new File(getCacheDir(), "crop_dest.png");
            mPickedItem = data.getData();
            if (!copyUriToFile(mPickedItem, cropSrc)) {
                setResult(Activity.RESULT_CANCELED);
                finish();
                return;
            }

            mCropSrc = FileProvider.getUriForFile(WidgetConfigure.this, "com.android.gallery3d.fileprovider",
                    new File(cropSrc.getAbsolutePath()));
            mCropDst = FileProvider.getUriForFile(WidgetConfigure.this, "com.android.gallery3d.fileprovider",
                    new File(cropDst.getAbsolutePath()));

            Intent request = new Intent(CropActivity.CROP_ACTION).putExtra(CropExtras.KEY_OUTPUT_X, widgetWidth)
                    .putExtra(CropExtras.KEY_OUTPUT_Y, widgetHeight)
                    .putExtra(CropExtras.KEY_ASPECT_X, widgetWidth)
                    .putExtra(CropExtras.KEY_ASPECT_Y, widgetHeight)
                    .putExtra(CropExtras.KEY_SCALE_UP_IF_NEEDED, true).putExtra(CropExtras.KEY_SCALE, true)
                    .putExtra(CropExtras.KEY_RETURN_DATA, false).setDataAndType(mCropSrc, "image/*")
                    .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            request.putExtra(MediaStore.EXTRA_OUTPUT, mCropDst);
            request.setClipData(ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, mCropDst));
            startActivityForResult(request, REQUEST_CROP_IMAGE);
        }
    });
}

From source file:com.just.agentweb.AgentWebUtils.java

static void grantPermissions(Context context, Intent intent, Uri uri, boolean writeAble) {

    int flag = Intent.FLAG_GRANT_READ_URI_PERMISSION;
    if (writeAble) {
        flag |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
    }//from  w ww .  j a  v a  2s  .c  o  m
    intent.addFlags(flag);
    List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        context.grantUriPermission(packageName, uri, flag);
    }
}

From source file:com.android.settings.users.EditUserPhotoController.java

private void appendOutputExtra(Intent intent, Uri pictureUri) {
    intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setClipData(ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, pictureUri));
}

From source file:com.commonsware.android.diceware.PassphraseFragment.java

private static boolean obtainDurablePermission(ContentResolver resolver, Uri document) {
    boolean weHaveDurablePermission = false;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

        try {/*w w w  .  jav a 2  s  . c om*/
            resolver.takePersistableUriPermission(document, perms);

            for (UriPermission perm : resolver.getPersistedUriPermissions()) {
                if (perm.getUri().equals(document)) {
                    weHaveDurablePermission = true;
                }
            }
        } catch (SecurityException e) {
            // OK, we were not offered any persistable permissions
        }
    }

    return (weHaveDurablePermission);
}

From source file:com.jefftharris.passwdsafe.StorageFileListFragment.java

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new AsyncTaskLoader<Cursor>(getActivity()) {
        /** Handle when the loader is reset */
        @Override/*from  w w  w. j  a v  a 2s .c  o m*/
        protected void onReset() {
            super.onReset();
            onStopLoading();
        }

        /** Handle when the loader is started */
        @Override
        protected void onStartLoading() {
            forceLoad();
        }

        /** Handle when the loader is stopped */
        @Override
        protected void onStopLoading() {
            cancelLoad();
        }

        /** Load the files in the background */
        @Override
        public Cursor loadInBackground() {
            PasswdSafeUtil.dbginfo(TAG, "loadInBackground");
            int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
            ContentResolver cr = getContext().getContentResolver();
            List<Uri> permUris = ApiCompat.getPersistedUriPermissions(cr);
            for (Uri permUri : permUris) {
                PasswdSafeUtil.dbginfo(TAG, "Checking persist perm %s", permUri);
                Cursor cursor = null;
                try {
                    cursor = cr.query(permUri, null, null, null, null);
                    if ((cursor != null) && (cursor.moveToFirst())) {
                        ApiCompat.takePersistableUriPermission(cr, permUri, flags);
                    } else {
                        ApiCompat.releasePersistableUriPermission(cr, permUri, flags);
                        itsRecentFilesDb.removeUri(permUri);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "File remove error: " + permUri, e);
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }

            try {
                return itsRecentFilesDb.queryFiles();
            } catch (Exception e) {
                Log.e(TAG, "Files load error", e);
            }
            return null;
        }
    };
}

From source file:com.xbm.android.matisse.ui.MatisseActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK)
        return;//from w  w w .  j a va  2  s.  com

    if (requestCode == REQUEST_CODE_PREVIEW) {
        Bundle resultBundle = data.getBundleExtra(BasePreviewActivity.EXTRA_RESULT_BUNDLE);
        ArrayList<Item> selected = resultBundle.getParcelableArrayList(SelectedItemCollection.STATE_SELECTION);
        int collectionType = resultBundle.getInt(SelectedItemCollection.STATE_COLLECTION_TYPE,
                SelectedItemCollection.COLLECTION_UNDEFINED);
        if (data.getBooleanExtra(BasePreviewActivity.EXTRA_RESULT_APPLY, false)) {
            Intent result = new Intent();
            ArrayList<Uri> selectedUris = new ArrayList<>();
            ArrayList<String> selectedPaths = new ArrayList<>();
            if (selected != null) {
                for (Item item : selected) {
                    selectedUris.add(item.getContentUri());
                    selectedPaths.add(PathUtils.getPath(this, item.getContentUri()));
                }
            }
            result.putParcelableArrayListExtra(EXTRA_RESULT_SELECTION, selectedUris);
            result.putStringArrayListExtra(EXTRA_RESULT_SELECTION_PATH, selectedPaths);
            setResult(RESULT_OK, result);
            finish();
        } else {
            mSelectedCollection.overwrite(selected, collectionType);
            Fragment mediaSelectionFragment = getSupportFragmentManager()
                    .findFragmentByTag(MediaSelectionFragment.class.getSimpleName());
            if (mediaSelectionFragment instanceof MediaSelectionFragment) {
                ((MediaSelectionFragment) mediaSelectionFragment).refreshMediaGrid();
            }
            updateBottomToolbar();
        }
    } else if (requestCode == REQUEST_CODE_CAPTURE) {
        // Just pass the data back to previous calling Activity.
        Uri contentUri = mMediaStoreCompat.getCurrentPhotoUri();
        String path = mMediaStoreCompat.getCurrentPhotoPath();
        ArrayList<Uri> selected = new ArrayList<>();
        selected.add(contentUri);
        ArrayList<String> selectedPath = new ArrayList<>();
        selectedPath.add(path);
        Intent result = new Intent();
        result.putParcelableArrayListExtra(EXTRA_RESULT_SELECTION, selected);
        result.putStringArrayListExtra(EXTRA_RESULT_SELECTION_PATH, selectedPath);
        setResult(RESULT_OK, result);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            MatisseActivity.this.revokeUriPermission(contentUri,
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        finish();
    }
}

From source file:com.slim.turboeditor.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();
            File newFile = new File(data.getPath());

            newFileToOpen(newFile, "");
        } else {//from w  w w  .  java2  s  . c  o  m

            final Uri data = intent.getData();
            final File newFile = new File(data.getPath());

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

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

                newFileToOpen(newFile, "");
            }

            if (requestCode == SAVE_AS_REQUEST_CODE) {
                getSaveFileObservable(getApplicationContext(), newFile,
                        pageSystem.getAllText(mEditor.getText().toString()), currentEncoding)
                                .subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<Boolean>() {
                                    @Override
                                    public void call(Boolean aBoolean) {
                                        savedAFile(aBoolean);
                                        newFileToOpen(newFile, "");
                                    }
                                });
            }
        }
    }
}

From source file:com.xperia64.timidityae.SettingsActivity.java

@SuppressLint("NewApi")
@Override//  w  ww .  j av  a2s  .com
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == 42) {
        if (resultCode == RESULT_OK) {
            Uri treeUri = data.getData();
            getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Globals.theFold = treeUri;
        } else {
            Globals.theFold = null;
        }

    }
}