Example usage for android.content Context grantUriPermission

List of usage examples for android.content Context grantUriPermission

Introduction

In this page you can find the example usage for android.content Context grantUriPermission.

Prototype

public abstract void grantUriPermission(String toPackage, Uri uri, @Intent.GrantUriMode int modeFlags);

Source Link

Document

Grant permission to access a specific Uri to another package, regardless of whether that package has general permission to access the Uri's content provider.

Usage

From source file:ca.rmen.android.scrumchatter.export.Export.java

/**
 * Bring up the chooser to send the file.
 *///from w  ww  .  j a va 2  s  .c  o m
static void share(Context context, File file, String mimeType) {
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.export_message_subject));
    sendIntent.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.export_message_body));
    Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", file);
    sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
    sendIntent.setType(mimeType);
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
        List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(sendIntent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Log.v(TAG, "grant permission to " + packageName);
        }
    }
    context.startActivity(
            Intent.createChooser(sendIntent, context.getResources().getText(R.string.action_share)));
}

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 ww w .  j ava2s.  co 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.ultramegasoft.flavordex2.util.PhotoUtils.java

/**
 * Get an Intent to capture a photo./*from  w  w w.  jav  a  2s  .co m*/
 *
 * @return Image capture Intent
 */
@Nullable
public static Intent getTakePhotoIntent(@NonNull Context context) {
    try {
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        final Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider",
                getOutputMediaFile());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            intent.setClipData(ClipData.newUri(context.getContentResolver(), null, uri));
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            final List<ResolveInfo> activities = context.getPackageManager().queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo activity : activities) {
                final String name = activity.activityInfo.packageName;
                context.grantUriPermission(name, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        }

        return intent;
    } catch (IOException e) {
        Log.e(TAG, "Failed to create new file", e);
    }
    return null;
}

From source file:org.fs.galleon.presenters.ToolsFragmentPresenter.java

private void dispatchTakePictureIntent() {
    createIfNotExists().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(file -> {/*from   w ww . j a v a  2  s .  c om*/
                if (file.exists()) {
                    log(Log.INFO, String.format(Locale.ENGLISH, "%s is temp file.", file.getAbsolutePath()));
                }
                if (view.isAvailable()) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (intent.resolveActivity(view.getContext().getPackageManager()) != null) {
                        this.tempTakenPhoto = file;//set it in property
                        Uri uri = FileProvider.getUriForFile(view.getContext(), GRANT_PERMISSION, file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        //fileProvider requires gran permission to others access that uri
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                            final Context context = view.getContext();
                            List<ResolveInfo> infos = context.getPackageManager().queryIntentActivities(intent,
                                    PackageManager.MATCH_DEFAULT_ONLY);
                            if (infos != null) {
                                StreamSupport.stream(infos).filter(x -> x.activityInfo != null)
                                        .map(x -> x.activityInfo.packageName).forEach(pack -> {
                                            context.grantUriPermission(pack, uri,
                                                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                                                            | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                        });
                            }
                        }
                        view.startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                    } else {
                        view.showError("You need to install app that can capture photo.");
                    }
                }
            }, this::log);
}

From source file:io.github.pwlin.cordova.plugins.fileopener2.FileOpener2.java

private void _open(String fileArg, String contentType, CallbackContext callbackContext) throws JSONException {
    String fileName = "";
    try {//from  w  w w .j av a2  s .com
        CordovaResourceApi resourceApi = webView.getResourceApi();
        Uri fileUri = resourceApi.remapUri(Uri.parse(fileArg));
        fileName = this.stripFileProtocol(fileUri.toString());
    } catch (Exception e) {
        fileName = fileArg;
    }
    File file = new File(fileName);
    if (file.exists()) {
        try {
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= 24) {

                Context context = cordova.getActivity().getApplicationContext();
                path = FileProvider.getUriForFile(context,
                        cordova.getActivity().getPackageName() + ".opener.provider", file);
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                List<ResolveInfo> infoList = context.getPackageManager().queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : infoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, path,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            } else {
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            }
            /*
             * @see
             * http://stackoverflow.com/questions/14321376/open-an-activity-from-a-cordovaplugin
             */
            cordova.getActivity().startActivity(intent);
            //cordova.getActivity().startActivity(Intent.createChooser(intent,"Open File in..."));
            callbackContext.success();
        } catch (android.content.ActivityNotFoundException e) {
            JSONObject errorObj = new JSONObject();
            errorObj.put("status", PluginResult.Status.ERROR.ordinal());
            errorObj.put("message", "Activity not found: " + e.getMessage());
            callbackContext.error(errorObj);
        }
    } else {
        JSONObject errorObj = new JSONObject();
        errorObj.put("status", PluginResult.Status.ERROR.ordinal());
        errorObj.put("message", "File not found");
        callbackContext.error(errorObj);
    }
}

From source file:nuclei.ui.share.PackageTargetManager.java

protected void onSetFileProvider(Context context, String packageName, String authority, Intent intent) {
    if (mUri != null || mFile != null) {
        Uri uri = mUri;/*w  w w  .j a  v  a 2 s.c  o  m*/
        String type = "*/*";
        if (mFile != null) {
            uri = FileProvider.getUriForFile(context, authority, mFile);
            final int lastDot = mFile.getName().lastIndexOf('.');
            if (lastDot >= 0) {
                String extension = mFile.getName().substring(lastDot + 1);
                String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                if (mimeType != null)
                    type = mimeType;
            }
        }
        intent.setDataAndType(intent.getData(), type);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        if (packageName != null) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    } else {
        intent.setType("text/plain");
    }
}

From source file:cz.maresmar.sfm.app.SfmApp.java

private void sendFeedback(Context context, String subject) {
    Timber.i("Device %s (%s) on SDK %d", Build.DEVICE, Build.MANUFACTURER, Build.VERSION.SDK_INT);

    File logFile = getLogFile();//from  w  w w  . j a  va2  s .  c  o m
    Uri logUri = FileProvider.getUriForFile(this, "cz.maresmar.sfm.FileProvider", logFile);

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "mmrmartin+dev" + '@' + "gmail.com" });
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "[sfm] " + subject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.feedback_mail_text));
    emailIntent.putExtra(Intent.EXTRA_STREAM, logUri);
    emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(emailIntent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        context.grantUriPermission(packageName, logUri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

    context.startActivity(
            Intent.createChooser(emailIntent, getString(R.string.feedback_choose_email_app_dialog)));
}

From source file:com.xbm.android.matisse.internal.utils.MediaStoreCompat.java

public void dispatchCaptureIntent(Context context, int requestCode) {
    Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (captureIntent.resolveActivity(context.getPackageManager()) != null) {
        File photoFile = null;/*w  w  w  . j a  va  2 s.  co  m*/
        try {
            photoFile = createImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (photoFile != null) {
            mCurrentPhotoPath = photoFile.getAbsolutePath();
            mCurrentPhotoUri = FileProvider.getUriForFile(mContext.get(), mCaptureStrategy.authority,
                    photoFile);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoUri);
            captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(captureIntent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, mCurrentPhotoUri,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            }
            if (mFragment != null) {
                mFragment.get().startActivityForResult(captureIntent, requestCode);
            } else {
                mContext.get().startActivityForResult(captureIntent, requestCode);
            }
        }
    }
}

From source file:io.nuclei.cyto.share.PackageTargetManager.java

/**
 * Set default intent data/*  w ww  .ja  va 2s . c o  m*/
 */
protected void onSetDefault(Context context, String packageName, String authority, Intent intent, String text) {
    intent.putExtra(Intent.EXTRA_TEXT, text);
    if (!TextUtils.isEmpty(mSubject))
        intent.putExtra(Intent.EXTRA_SUBJECT, mSubject);
    if (mUri != null || mFile != null) {
        Uri uri = mUri;
        String type = "*/*";
        if (mFile != null) {
            uri = FileProvider.getUriForFile(context, authority, mFile);
            final int lastDot = mFile.getName().lastIndexOf('.');
            if (lastDot >= 0) {
                String extension = mFile.getName().substring(lastDot + 1);
                String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                if (mimeType != null)
                    type = mimeType;
            }
        }
        intent.setDataAndType(intent.getData(), type);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        if (packageName != null) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    } else {
        intent.setType("text/plain");
    }
    if (!TextUtils.isEmpty(mEmail)) {
        intent.putExtra(Intent.EXTRA_EMAIL, new String[] { mEmail });
        intent.setData(Uri.parse("mailto:"));
    }
}

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

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