Example usage for android.content Intent FLAG_GRANT_READ_URI_PERMISSION

List of usage examples for android.content Intent FLAG_GRANT_READ_URI_PERMISSION

Introduction

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

Prototype

int FLAG_GRANT_READ_URI_PERMISSION

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

Click Source Link

Document

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

Usage

From source file:com.amaze.filemanager.ui.views.drawer.Drawer.java

public void onActivityResult(int requestCode, int responseCode, Intent intent) {
    if (mainActivity.getPrefs() != null && intent != null && intent.getData() != null) {
        if (SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mainActivity.getContentResolver().takePersistableUriPermission(intent.getData(),
                    Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }//from   w w w  . j  a v  a  2  s .  c om
        mainActivity.getPrefs().edit()
                .putString(PreferencesConstants.PREFERENCE_DRAWER_HEADER_PATH, intent.getData().toString())
                .commit();
        setDrawerHeaderBackground();
    }
}

From source file:org.sufficientlysecure.keychain.ui.DecryptListFragment.java

public void displayWithViewIntent(InputDataResult result, int index, boolean share, boolean forceChooser) {
    Activity activity = getActivity();//w  w w  .j  a  va 2 s  .  c  o m
    if (activity == null) {
        return;
    }

    Uri outputUri = result.getOutputUris().get(index);
    OpenPgpMetadata metadata = result.mMetadata.get(index);

    // text/plain is a special case where we extract the uri content into
    // the EXTRA_TEXT extra ourselves, and display a chooser which includes
    // OpenKeychain's internal viewer
    if ("text/plain".equals(metadata.getMimeType())) {

        if (share) {
            try {
                String plaintext = FileHelper.readTextFromUri(activity, outputUri, null);

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, plaintext);

                Intent chooserIntent = Intent.createChooser(intent, getString(R.string.intent_share));
                startActivity(chooserIntent);

            } catch (IOException e) {
                Notify.create(activity, R.string.error_preparing_data, Style.ERROR).show();
            }

            return;
        }

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(outputUri, "text/plain");

        if (forceChooser) {

            LabeledIntent internalIntent = new LabeledIntent(
                    new Intent(intent).setClass(activity, DisplayTextActivity.class)
                            .putExtra(DisplayTextActivity.EXTRA_RESULT, result.mDecryptVerifyResult)
                            .putExtra(DisplayTextActivity.EXTRA_METADATA, metadata),
                    BuildConfig.APPLICATION_ID, R.string.view_internal, R.mipmap.ic_launcher);

            Intent chooserIntent = Intent.createChooser(intent, getString(R.string.intent_show));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { internalIntent });

            startActivity(chooserIntent);

        } else {

            intent.setClass(activity, DisplayTextActivity.class);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra(DisplayTextActivity.EXTRA_RESULT, result.mDecryptVerifyResult);
            intent.putExtra(DisplayTextActivity.EXTRA_METADATA, metadata);
            startActivity(intent);

        }

    } else {

        Intent intent;
        if (share) {
            intent = new Intent(Intent.ACTION_SEND);
            intent.setType(metadata.getMimeType());
            intent.putExtra(Intent.EXTRA_STREAM, outputUri);
        } else {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(outputUri, metadata.getMimeType());

            if (!forceChooser && Constants.MIME_TYPE_KEYS.equals(metadata.getMimeType())) {
                // bind Intent to this OpenKeychain, don't allow other apps to intercept here!
                intent.setPackage(getActivity().getPackageName());
            }
        }

        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        Intent chooserIntent = Intent.createChooser(intent, getString(R.string.intent_show));
        chooserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        if (!share && ClipDescription.compareMimeTypes(metadata.getMimeType(), "text/*")) {
            LabeledIntent internalIntent = new LabeledIntent(
                    new Intent(intent).setClass(activity, DisplayTextActivity.class)
                            .putExtra(DisplayTextActivity.EXTRA_RESULT, result.mDecryptVerifyResult)
                            .putExtra(DisplayTextActivity.EXTRA_METADATA, metadata),
                    BuildConfig.APPLICATION_ID, R.string.view_internal, R.mipmap.ic_launcher);
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { internalIntent });
        }

        startActivity(chooserIntent);
    }

}

From source file:com.brq.wallet.activity.modern.ModernMain.java

private void shareTransactionHistory() {
    WalletAccount account = _mbwManager.getSelectedAccount();
    MetadataStorage metaData = _mbwManager.getMetadataStorage();
    try {//from w  w  w  .ja v a  2s . c om
        String fileName = "MyceliumExport_" + System.currentTimeMillis() + ".csv";
        File historyData = DataExport.getTxHistoryCsv(account, metaData, getFileStreamPath(fileName));
        PackageManager packageManager = Preconditions.checkNotNull(getPackageManager());
        PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_PROVIDERS);
        for (ProviderInfo info : packageInfo.providers) {
            if (info.name.equals("android.support.v4.content.FileProvider")) {
                String authority = info.authority;
                Uri uri = FileProvider.getUriForFile(this, authority, historyData);
                Intent intent = ShareCompat.IntentBuilder.from(this).setStream(uri) // uri from FileProvider
                        .setType("text/plain")
                        .setSubject(getResources().getString(R.string.transaction_history_title))
                        .setText(getResources().getString(R.string.transaction_history_title)).getIntent()
                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                List<ResolveInfo> resInfoList = packageManager.queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                startActivity(Intent.createChooser(intent,
                        getResources().getString(R.string.share_transaction_history)));
            }
        }
    } catch (IOException e) {
        _toaster.toast("Export failed. Check your logs", false);
        e.printStackTrace();
    } catch (PackageManager.NameNotFoundException e) {
        _toaster.toast("Export failed. Check your logs", false);
        e.printStackTrace();
    }
}

From source file:com.amaze.filemanager.utils.files.FileUtils.java

public static void openWith(final DocumentFile f, final Context c, final boolean useNewStack) {
    MaterialDialog.Builder a = new MaterialDialog.Builder(c);
    a.title(c.getString(R.string.openas));
    String[] items = new String[] { c.getString(R.string.text), c.getString(R.string.image),
            c.getString(R.string.video), c.getString(R.string.audio), c.getString(R.string.database),
            c.getString(R.string.other) };

    a.items(items).itemsCallback((materialDialog, view, i, charSequence) -> {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        switch (i) {
        case 0://from   w w  w .  j ava 2 s  .co m
            if (useNewStack)
                applyNewDocFlag(intent);
            intent.setDataAndType(f.getUri(), "text/*");
            break;
        case 1:
            intent.setDataAndType(f.getUri(), "image/*");
            break;
        case 2:
            intent.setDataAndType(f.getUri(), "video/*");
            break;
        case 3:
            intent.setDataAndType(f.getUri(), "audio/*");
            break;
        case 4:
            intent = new Intent(c, DatabaseViewerActivity.class);
            intent.putExtra("path", f.getUri());
            break;
        case 5:
            intent.setDataAndType(f.getUri(), "*/*");
            break;
        }
        try {
            c.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c, useNewStack);
        }
    });

    a.build().show();
}

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

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

From source file:com.mb.android.MainActivity.java

@android.webkit.JavascriptInterface
@org.xwalk.core.JavascriptInterface//w  w  w  .j a  v  a 2  s  .  co 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:de.baumann.browser.helper.helper_main.java

private static void openFile(Activity activity, File file, String string, View view) {

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri contentUri = FileProvider.getUriForFile(activity,
                activity.getApplicationContext().getPackageName() + ".provider", file);
        intent.setDataAndType(contentUri, string);

    } else {//from   w  ww  .j a  v  a 2s .c o m
        intent.setDataAndType(Uri.fromFile(file), string);
    }

    try {
        activity.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Snackbar.make(view, R.string.toast_install_app, Snackbar.LENGTH_LONG).show();
    }
}

From source file:com.android.contacts.activities.ContactSelectionActivity.java

public void returnPickerResult(Intent intent) {
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    setResult(RESULT_OK, intent);
    finish();
}

From source file:net.emilymaier.movebot.MoveBotActivity.java

/**
 * Generate a run's .gpx file and share it.
 * @param run the run session to generate the .gpx from
 *///from   w  w w  .j  ava  2  s.c om
private void shareGpx(Run run) {
    String filename;
    try {
        filename = run.generateGpx(this);
    } catch (IOException e) {
        throw new RuntimeException("IOException", e);
    }
    File gpxFile = new File(getFilesDir(), filename);
    Uri gpxUri = FileProvider.getUriForFile(this, "net.emilymaier.movebot.fileprovider", gpxFile);
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_STREAM, gpxUri);
    sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    sendIntent.setType("application/xml");
    startActivity(sendIntent);
}

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  www  . j a v a  2  s  . 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;
        }
    }
}