Example usage for android.content Intent FLAG_GRANT_PERSISTABLE_URI_PERMISSION

List of usage examples for android.content Intent FLAG_GRANT_PERSISTABLE_URI_PERMISSION

Introduction

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

Prototype

int FLAG_GRANT_PERSISTABLE_URI_PERMISSION

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

Click Source Link

Document

When combined with #FLAG_GRANT_READ_URI_PERMISSION and/or #FLAG_GRANT_WRITE_URI_PERMISSION , the URI permission grant can be persisted across device reboots until explicitly revoked with Context#revokeUriPermission(Uri,int) .

Usage

From source file:org.andstatus.app.util.UriUtils.java

/** See http://developer.android.com/guide/topics/providers/document-provider.html */
@TargetApi(Build.VERSION_CODES.KITKAT)//from  ww  w  . j av a 2s .  c  om
public static int flagsToTakePersistableUriPermission() {
    int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        flags = flags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
    }
    return flags;
}

From source file:org.jak_linux.dns66.ItemActivity.java

public void performFileSearch() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);

    startActivityForResult(intent, READ_REQUEST_CODE);
}

From source file:org.andstatus.app.util.UriUtils.java

/** See http://stackoverflow.com/questions/25999886/android-content-provider-uri-doesnt-work-after-reboot */
@TargetApi(Build.VERSION_CODES.KITKAT)/*from w w w  .  j a  v a2 s.  co m*/
public static void takePersistableUriPermission(Context context, Uri uri, int takeFlagsIn) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        return;
    }
    if ((takeFlagsIn & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) {
        final int takeFlags = takeFlagsIn
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        try {
            context.getContentResolver().takePersistableUriPermission(uri, takeFlags);
        } catch (SecurityException e) {
            MyLog.i(context, "Exception while taking persistable URI permission for '" + uri + "'", e);
        }
    } else {
        MyLog.i(context, "No persistable URI permission for '" + uri + "'");
    }
}

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

private void grantPersistableReadPermission(Uri uri) throws Exception {
    Intent grantPersistable = new Intent(ACTION_TAKE_PERSISTABLE_URI_PERMISSION);
    grantPersistable.setClipData(ClipData.newRawUri("", uri));
    grantPersistable/*from   w ww  .j av  a  2 s  . co  m*/
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
    mActivity.getResult(grantPersistable);
}

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

private void grantPersistableReadPermission(Uri uri) throws Exception {
    Intent grantPersistable = new Intent(ACTION_TAKE_PERSISTABLE_URI_PERMISSION);
    grantPersistable.setClipData(ClipData.newRawUri("", uri));
    grantPersistable//from   w w w  .  j  a v  a 2  s. c o m
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
    mActivity.getCrossProfileResult(grantPersistable);
}

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

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

    fileHistory = App.getFileHistory();/*from w  w w .  ja v a2 s .  c o  m*/

    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:ml.puredark.hviewer.ui.fragments.SettingFragment.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getPreferenceManager().setSharedPreferencesName(SharedPreferencesUtil.FILE_NAME);
    addPreferencesFromResource(R.xml.preferences);

    String downloadPath = DownloadManager.getDownloadPath();
    if (downloadPath != null) {
        String displayPath = Uri.decode(downloadPath);
        getPreferenceManager().findPreference(KEY_PREF_DOWNLOAD_PATH).setSummary(displayPath);
    }// w w  w. j a va 2s  . c o  m
    ListPreference listPreference = (ListPreference) getPreferenceManager()
            .findPreference(KEY_PREF_VIEW_DIRECTION);
    CharSequence[] entries = listPreference.getEntries();
    int i = listPreference.findIndexOfValue(listPreference.getValue());
    i = (i <= 0) ? 0 : i;
    listPreference.setSummary(entries[i]);
    listPreference.setOnPreferenceChangeListener(this);
    listPreference = (ListPreference) getPreferenceManager().findPreference(KEY_PREF_VIEW_VIDEO_PLAYER);
    entries = listPreference.getEntries();
    i = listPreference.findIndexOfValue(listPreference.getValue());
    i = (i <= 0) ? 0 : i;
    listPreference.setSummary(entries[i]);
    listPreference.setOnPreferenceChangeListener(this);

    getPreferenceScreen().setOnPreferenceChangeListener(this);
    final DirectoryChooserConfig config = DirectoryChooserConfig.builder()
            .initialDirectory((downloadPath.startsWith("/")) ? downloadPath : DownloadManager.DEFAULT_PATH)
            .newDirectoryName("download").allowNewDirectoryNameModification(true).build();
    mDialog = DirectoryChooserFragment.newInstance(config);
    mDialog.setTargetFragment(this, 0);

    float size = (float) Fresco.getImagePipelineFactory().getMainFileCache().getSize() / ByteConstants.MB;
    Preference cacheCleanPreference = getPreferenceManager().findPreference(KEY_PREF_CACHE_CLEAN);
    cacheCleanPreference.setSummary(String.format(" %.2f MB", size));

    LongClickPreference prefDownloadPath = (LongClickPreference) getPreferenceManager()
            .findPreference(KEY_PREF_DOWNLOAD_PATH);
    prefDownloadPath.setOnLongClickListener(v -> {
        new AlertDialog.Builder(activity).setTitle("?")
                .setItems(new String[] { "", "" },
                        (dialogInterface, pos) -> {
                            if (pos == 0 && 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);
                                try {
                                    startActivityForResult(intent, RESULT_CHOOSE_DIRECTORY);
                                } catch (ActivityNotFoundException e) {
                                    e.printStackTrace();
                                    mDialog.show(getFragmentManager(), null);
                                }
                                new Handler().postDelayed(() -> {
                                    if (!opened)
                                        activity.showSnackBar(
                                                "?");
                                }, 1000);
                            } else if (pos == 1) {
                                mDialog.show(getFragmentManager(), null);
                            } else
                                activity.showSnackBar("???");
                        })
                .setNegativeButton(getString(R.string.cancel), null).show();
        return true;
    });
}

From source file:de.k3b.android.toGoZip.SettingsActivity.java

private boolean openPicker(CharSequence oldFolder, int folderpickerCode, boolean useDocumentProvider) {
    if (!useDocumentProvider) {
        Intent intent = new Intent(SettingsActivity.this, FolderPicker.class);
        if ((oldFolder != null) && (oldFolder.length() > 0)) {
            intent.putExtra("location", oldFolder); // initial dir
        }/*w  w  w  .j a  va2s .  c  o m*/
        startActivityForResult(intent, folderpickerCode);
    } else {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        startActivityForResult(intent, folderpickerCode);
    }
    return true;
}

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

@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    if (preference.getKey().equals(KEY_PREF_ABOUT_UPGRADE)) {
        ///* w  ww  . j av a  2  s  .  c  o m*/
        if (!checking)
            UpdateManager.checkUpdate(activity);
    } else if (preference.getKey().equals(KEY_PREF_BKRS_BACKUP)) {
        //
        new AlertDialog.Builder(activity).setTitle("?").setMessage("?")
                .setPositiveButton(getString(R.string.ok), (dialog, which) -> {
                    String backup = new DataBackup().DoBackup();
                    activity.showSnackBar(backup);
                }).setNegativeButton(getString(R.string.cancel), null).show();

    } else if (preference.getKey().equals(KEY_PREF_BKRS_RESTORE)) {
        //
        new AlertDialog.Builder(activity).setTitle("???")
                .setMessage("????")
                .setPositiveButton(getString(R.string.ok), (dialog, which) -> {
                    String restore = new DataRestore().DoRestore();
                    Intent intent = new Intent();
                    activity.setResult(RESULT_OK, intent);
                    Toast.makeText(activity, restore, Toast.LENGTH_LONG).show();
                    activity.finish();
                }).setNegativeButton(getString(R.string.cancel), null).show();

    } else if (preference.getKey().equals(KEY_PREF_ABOUT_LICENSE)) {
        //???
        Intent intent = new Intent(activity, LicenseActivity.class);
        startActivity(intent);
    } else if (preference.getKey().equals(KEY_PREF_ABOUT_PRIVACY)) {
        //???
        Intent intent = new Intent(activity, PrivacyActivity.class);
        startActivity(intent);
    } else if (preference.getKey().equals(KEY_PREF_ABOUT_H_VIEWER)) {
        //
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.setting_content, new AboutFragment(activity));
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.addToBackStack(null);
        transaction.commit();
    } else if (preference.getKey().equals(KEY_PREF_DOWNLOAD_PATH)) {
        //
        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);
            try {
                startActivityForResult(intent, RESULT_CHOOSE_DIRECTORY);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                mDialog.show(getFragmentManager(), null);
            }
            new Handler().postDelayed(() -> {
                if (!opened)
                    activity.showSnackBar("?");
            }, 1000);
        } else {
            mDialog.show(getFragmentManager(), null);
        }
    } else if (preference.getKey().equals(KEY_PREF_DOWNLOAD_IMPORT)) {
        //
        new AlertDialog.Builder(activity).setTitle("?")
                .setMessage("??")
                .setPositiveButton(getString(R.string.ok), (dialog, which) -> {
                    DownloadedImport();
                }).setNegativeButton(getString(R.string.cancel), null).show();
    } else if (preference.getKey().equals(KEY_PREF_FAVOURITE_EXPORT)) {
        //?
        new AlertDialog.Builder(activity).setTitle("??")
                .setMessage("?")
                .setPositiveButton("", (dialog, which) -> {
                    DocumentFile file = FileHelper.createFileIfNotExist(Names.favouritesname,
                            DownloadManager.getDownloadPath(), Names.backupdirname);
                    if (file != null) {
                        FavouriteHolder holder = new FavouriteHolder(activity);
                        String json = new Gson().toJson(holder.getFavourites());
                        FileHelper.writeString(json, file);
                        holder.onDestroy();
                        activity.showSnackBar("??");
                    } else
                        activity.showSnackBar("");
                }).setNegativeButton(getString(R.string.cancel), null).show();
    } else if (preference.getKey().equals(KEY_PREF_FAVOURITE_IMPORT)) {
        //?
        new AlertDialog.Builder(activity).setTitle("??")
                .setMessage("???")
                .setPositiveButton(getString(R.string.ok), (dialog, which) -> {
                    String json = FileHelper.readString(Names.favouritesname, DownloadManager.getDownloadPath(),
                            Names.backupdirname);
                    if (json == null) {
                        activity.showSnackBar("?");
                    } else {
                        try {
                            List<Pair<CollectionGroup, List<LocalCollection>>> favGroups = new Gson().fromJson(
                                    json,
                                    new TypeToken<ArrayList<Pair<CollectionGroup, ArrayList<LocalCollection>>>>() {
                                    }.getType());
                            FavouriteHolder holder = new FavouriteHolder(activity);
                            for (Pair<CollectionGroup, List<LocalCollection>> pair : favGroups) {
                                Logger.d("DataStore", "" + pair.first);
                                CollectionGroup group = holder.getGroupByTitle(pair.first.title);
                                if (group == null) {
                                    group = pair.first;
                                    group.gid = holder.addFavGroup(group);
                                }
                                for (LocalCollection collection : pair.second) {
                                    collection.gid = group.gid;
                                    holder.addFavourite(collection);
                                }
                            }
                            holder.onDestroy();
                            activity.showSnackBar("??");
                        } catch (Exception e) {
                            e.printStackTrace();
                            activity.showSnackBar("?");
                        }
                    }
                }).setNegativeButton(getString(R.string.cancel), null).show();
    } else if (preference.getKey().equals(KEY_PREF_CACHE_CLEAN)) {
        //
        new AlertDialog.Builder(activity).setTitle("?")
                .setMessage("??")
                .setPositiveButton(getString(R.string.ok), (dialog, which) -> {
                    ImagePipeline imagePipeline = Fresco.getImagePipeline();
                    imagePipeline.clearDiskCaches();
                    activity.showSnackBar("??");
                    preference.setSummary(" 0.00 MB");
                }).setNegativeButton(getString(R.string.cancel), null).show();
    } else if (preference.getKey().equals(KEY_PREF_PROXY_DETAIL)) {
        //PROXY?
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.setting_content, new ProxyFragment(activity));
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.addToBackStack(null);
        transaction.commit();
    } else if (preference.getKey().equals(KEY_PREF_LOCK_METHODS_DETAIL)) {
        //??
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.setting_content, new LockMethodFragment(activity));
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.addToBackStack(null);
        transaction.commit();
    }
    return super.onPreferenceTreeClick(preferenceScreen, preference);
}

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

@Override
public Uri canonicalize(@NonNull Uri uri) {
    try {/*from  w  w w.  j  a va2 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;
    }
}