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:java_lang_programming.com.android_media_demo.ImageSelectionCropDemo.java

/**
 * start Crop/*from  w  w w . j a  v a2s  .c o m*/
 *
 * @param uri image uri
 */
private void startCrop(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("aspectX", 16);
    intent.putExtra("aspectY", 9);
    intent.putExtra("scaleUpIfNeeded", true);
    intent.putExtra("scale", "true");
    intent.putExtra("return-data", false);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.name());
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getExternalStorageTempStoreFilePath()));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    startActivityForResult(intent, ImageSelectionCropDemo.REQUEST_CODE_CROP);
}

From source file:us.rader.tapset.ShowQrCodeActivity.java

/**
 * Save {@link #bitmap} to a file and then send a sharing {@link Intent}
 * wrapped in a chooser/*from ww  w.ja  va2 s  . c om*/
 * 
 * @see Intent#ACTION_SEND
 * @see Intent#createChooser(Intent, CharSequence)
 * @see Activity#startActivity(Intent)
 */
private void shareQrCode() {

    try {

        File file = getFileStreamPath("tapset_qr.png"); //$NON-NLS-1$
        FileOutputStream stream = openFileOutput(file.getName(), 0);

        try {

            bitmap.compress(CompressFormat.PNG, 100, stream);

        } finally {

            stream.close();

        }

        String label = getString(R.string.share_label_text);
        Uri uri = FileProvider.getContentUri(getString(R.string.provider_authority_file), file.getName());
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setData(uri);
        intent.setType(FileProvider.getMimeType(uri));
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Intent chooser = Intent.createChooser(intent, label);
        startActivity(chooser);

    } catch (Exception e) {

        // ignore errors here

    }
}

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  .  ja  va 2  s. c  o m
    } else {
        intent.setData(Uri.fromFile(file));
    }
}

From source file:org.physical_web.physicalweb.BluetoothSite.java

private void openInChrome(File file) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri contentUri = new FileProvider().getUriForFile(activity, "org.physical_web.fileprovider", file);
    activity.grantUriPermission("com.android.chrome", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setDataAndType(contentUri, "text/html");
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    activity.startActivity(intent);/*  w  w w.  j a  v  a2 s. c om*/
}

From source file:de.schildbach.wallet.ui.ReportIssueDialogBuilder.java

private void startSend(final CharSequence subject, final CharSequence text, final ArrayList<Uri> attachments) {
    final Intent intent;

    if (attachments.size() == 0) {
        intent = new Intent(Intent.ACTION_SEND);
        intent.setType("message/rfc822");
    } else if (attachments.size() == 1) {
        intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_STREAM, attachments.get(0));
    } else {/*from w ww.j  a va 2 s  .c  o  m*/
        intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        intent.setType("text/plain");
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachments);
    }

    intent.putExtra(Intent.EXTRA_EMAIL, new String[] { Constants.REPORT_EMAIL });
    if (subject != null)
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, text);

    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        context.startActivity(Intent.createChooser(intent,
                context.getString(R.string.report_issue_dialog_mail_intent_chooser)));
        log.info("invoked chooser for sending issue report");
    } catch (final Exception x) {
        Toast.makeText(context, R.string.report_issue_dialog_mail_intent_failed, Toast.LENGTH_LONG).show();
        log.error("report issue failed", x);
    }
}

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

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

    fileHistory = App.getFileHistory();//w  w w  .  j  a  va 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:ru.dublgis.androidhelpers.DesktopUtils.java

public static boolean sendEmail(final Context ctx, final String to, final String subject, final String body,
        final String attach_file, final boolean force_content_provider, final String authorities) {
    //Log.d(TAG, "Will send email with subject \"" +
    //    subject + "\" to \"" + to + "\" with attach_file = \"" + attach_file + "\"" +
    //    ", force_content_provider = " + force_content_provider +
    //    ", authorities = \"" + authorities + "\"");
    try {//from  w ww.  ja v a 2 s.  c  o m
        // TODO: support multiple recipients
        String[] recipients = new String[] { to };

        final Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", to, null));
        List<ResolveInfo> resolveInfos = ctx.getPackageManager().queryIntentActivities(intent, 0);
        Intent chooserIntent = null;
        List<Intent> intentList = new ArrayList<Intent>();

        Intent i = new Intent(Intent.ACTION_SEND);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_EMAIL, recipients);
        i.putExtra(Intent.EXTRA_SUBJECT, subject);
        i.putExtra(Intent.EXTRA_TEXT, body);

        Uri workaround_grant_permission_for_uri = null;
        if (attach_file != null && !attach_file.isEmpty()) {
            if (!force_content_provider && android.os.Build.VERSION.SDK_INT < 23) {
                i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(attach_file)));
            } else {
                // Android 6+: going the longer route.
                // For more information, please see:
                // http://stackoverflow.com/questions/32981194/android-6-cannot-share-files-anymore
                i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                workaround_grant_permission_for_uri = FileProvider.getUriForFile(ctx, authorities,
                        new File(attach_file));
                i.putExtra(Intent.EXTRA_STREAM, workaround_grant_permission_for_uri);
            }
        }

        for (ResolveInfo resolveInfo : resolveInfos) {
            String packageName = resolveInfo.activityInfo.packageName;
            String name = resolveInfo.activityInfo.name;

            // Some mail clients will not read the URI unless this is done.
            // See here: https://stackoverflow.com/questions/24467696/android-file-provider-permission-denial
            if (workaround_grant_permission_for_uri != null) {
                try {
                    ctx.grantUriPermission(packageName, workaround_grant_permission_for_uri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } catch (final Throwable e) {
                    Log.e(TAG, "grantUriPermission error: ", e);
                }
            }

            Intent fakeIntent = (Intent) i.clone();
            fakeIntent.setComponent(new ComponentName(packageName, name));
            if (chooserIntent == null) {
                chooserIntent = fakeIntent;
            } else {
                intentList.add(fakeIntent);
            }
        }

        if (chooserIntent == null) {
            chooserIntent = Intent.createChooser(i, null // "Select email application."
            );
            chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else if (!intentList.isEmpty()) {
            Intent fakeIntent = chooserIntent;
            chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, fakeIntent);
            Intent[] extraIntents = intentList.toArray(new Intent[intentList.size()]);
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
        }

        ctx.startActivity(chooserIntent);
        return true;
    } catch (final Throwable e) {
        Log.e(TAG, "sendEmail exception: ", e);
        return false;
    }
}

From source file:com.giovanniterlingen.windesheim.controllers.DownloadController.java

@Override
protected void onPostExecute(final String result) {
    activeDownloads.remove(contentId);/*  ww  w  . ja va2 s  .  co m*/
    NotificationCenter.getInstance().removeObserver(this, NotificationCenter.downloadCancelled);
    NotificationCenter.getInstance().postNotificationName(NotificationCenter.downloadFinished, studyRouteId,
            adapterPosition, contentId);

    if ("permission".equals(result)) {
        ((NatschoolActivity) activity).noPermission();
        return;
    }
    if ("cancelled".equals(result)) {
        ((NatschoolActivity) activity).downloadCanceled();
        return;
    }
    if (result != null) {
        Uri uri;
        Intent target = new Intent(Intent.ACTION_VIEW);
        if (android.os.Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(activity, "com.giovanniterlingen.windesheim.provider",
                    new File(result));
            target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(new File(result));
            target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        }
        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(uri.toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        target.setDataAndType(uri, mimetype);
        try {
            activity.startActivity(target);
        } catch (ActivityNotFoundException e) {
            ((NatschoolActivity) activity).noSupportedApp();
        }
    }
}

From source file:de.j4velin.mapsmeasure.Dialogs.java

/**
 * @param c     the Context//  ww w .j  ava 2s.  c om
 * @param trace the current trace of points
 * @return the "save & share" dialog
 */
public static Dialog getSaveNShare(final Activity c, final Stack<LatLng> trace) {
    final Dialog d = new Dialog(c);
    d.requestWindowFeature(Window.FEATURE_NO_TITLE);
    d.setContentView(R.layout.dialog_save);
    d.findViewById(R.id.save).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            final File destination;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO
                    && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                destination = API8Wrapper.getExternalFilesDir(c);
            } else {
                destination = c.getDir("traces", Context.MODE_PRIVATE);
            }

            d.dismiss();
            AlertDialog.Builder b = new AlertDialog.Builder(c);
            b.setTitle(R.string.save);
            final View layout = c.getLayoutInflater().inflate(R.layout.dialog_enter_filename, null);
            ((TextView) layout.findViewById(R.id.location))
                    .setText(c.getString(R.string.file_path, destination.getAbsolutePath() + "/"));
            b.setView(layout);
            b.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        String fname = ((EditText) layout.findViewById(R.id.filename)).getText().toString();
                        if (fname == null || fname.length() < 1) {
                            fname = "MapsMeasure_" + System.currentTimeMillis();
                        }
                        final File f = new File(destination, fname + ".csv");
                        Util.saveToFile(f, trace);
                        d.dismiss();
                        Toast.makeText(c, c.getString(R.string.file_saved, f.getAbsolutePath()),
                                Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(c,
                                c.getString(R.string.error,
                                        e.getClass().getSimpleName() + "\n" + e.getMessage()),
                                Toast.LENGTH_LONG).show();
                    }
                }
            });
            b.create().show();
        }
    });
    d.findViewById(R.id.load).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {

            File[] files = c.getDir("traces", Context.MODE_PRIVATE).listFiles();

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO
                    && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File ext = API8Wrapper.getExternalFilesDir(c);
                // even though we checked the external storage state, ext is still sometims null, accoring to Play Store crash reports
                if (ext != null) {
                    File[] filesExtern = ext.listFiles();
                    File[] allFiles = new File[files.length + filesExtern.length];
                    System.arraycopy(files, 0, allFiles, 0, files.length);
                    System.arraycopy(filesExtern, 0, allFiles, files.length, filesExtern.length);
                    files = allFiles;
                }
            }

            if (files.length == 0) {
                Toast.makeText(c,
                        c.getString(R.string.no_files_found,
                                c.getDir("traces", Context.MODE_PRIVATE).getAbsolutePath()),
                        Toast.LENGTH_SHORT).show();
            } else if (files.length == 1) {
                try {
                    Util.loadFromFile(Uri.fromFile(files[0]), (Map) c);
                    d.dismiss();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(c,
                            c.getString(R.string.error, e.getClass().getSimpleName() + "\n" + e.getMessage()),
                            Toast.LENGTH_LONG).show();
                }
            } else {
                d.dismiss();
                AlertDialog.Builder b = new AlertDialog.Builder(c);
                b.setTitle(R.string.select_file);
                final DeleteAdapter da = new DeleteAdapter(files, (Map) c);
                b.setAdapter(da, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            Util.loadFromFile(Uri.fromFile(da.getFile(which)), (Map) c);
                            dialog.dismiss();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(c,
                                    c.getString(R.string.error,
                                            e.getClass().getSimpleName() + "\n" + e.getMessage()),
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                });
                b.create().show();
            }
        }
    });
    d.findViewById(R.id.share).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            try {
                final File f = new File(c.getCacheDir(), "MapsMeasure.csv");
                Util.saveToFile(f, trace);
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM,
                        FileProvider.getUriForFile(c, "de.j4velin.mapsmeasure.fileprovider", f));
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                shareIntent.setType("text/comma-separated-values");
                d.dismiss();
                c.startActivity(Intent.createChooser(shareIntent, null));
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(c,
                        c.getString(R.string.error, e.getClass().getSimpleName() + "\n" + e.getMessage()),
                        Toast.LENGTH_LONG).show();
            }
        }
    });
    return d;
}