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.android.cts.verifier.managedprovisioning.NfcTestActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.byod_nfc_test_activity);

    mAdminReceiverComponent = new ComponentName(this, DeviceAdminTestReceiver.class.getName());
    mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mUserMangaer = (UserManager) getSystemService(Context.USER_SERVICE);
    mDisallowByPolicy = getIntent().getBooleanExtra(EXTRA_DISALLOW_BY_POLICY, false);
    if (mDisallowByPolicy) {
        mDevicePolicyManager.addUserRestriction(mAdminReceiverComponent, UserManager.DISALLOW_OUTGOING_BEAM);
    }/*from  www.ja  v a 2s . c o m*/

    final Uri uri = createUriForImage(SAMPLE_IMAGE_FILENAME, SAMPLE_IMAGE_CONTENT);
    Uri[] uris = new Uri[] { uri };

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    mNfcAdapter.setBeamPushUris(uris, this);

    findViewById(R.id.manual_beam_button).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            mNfcAdapter.invokeBeam(NfcTestActivity.this);
        }
    });
    findViewById(R.id.intent_share_button).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
            shareIntent.setType("image/jpg");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // Specify the package name of NfcBeamActivity so that the tester don't need to
            // select the activity manually.
            shareIntent.setClassName(NFC_BEAM_PACKAGE, NFC_BEAM_ACTIVITY);
            try {
                startActivity(shareIntent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(NfcTestActivity.this, R.string.provisioning_byod_cannot_resolve_beam_activity,
                        Toast.LENGTH_SHORT).show();
                Log.e(TAG, "Nfc beam activity not found", e);
            }
        }
    });
}

From source file:com.doplgangr.secrecy.views.FileViewer.java

void decrypt(final EncryptedFile encryptedFile, final Runnable onFinish) {
    new AsyncTask<EncryptedFile, Void, File>() {
        @Override/*from ww  w. j  a v  a2  s .co m*/
        protected File doInBackground(EncryptedFile... encryptedFiles) {
            return getFile(encryptedFile, onFinish);
        }

        @Override
        protected void onPostExecute(File tempFile) {
            if (tempFile != null) {
                if (tempFile.getParentFile().equals(Storage.getTempFolder())) {
                    tempFile = new File(Storage.getTempFolder(), tempFile.getName());
                }
                Uri uri = OurFileProvider.getUriForFile(context, OurFileProvider.FILE_PROVIDER_AUTHORITY,
                        tempFile);
                MimeTypeMap myMime = MimeTypeMap.getSingleton();
                Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);
                String mimeType = myMime.getMimeTypeFromExtension(encryptedFile.getType());
                newIntent.setDataAndType(uri, mimeType);
                newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                //altIntent: resort to using file provider when content provider does not work.
                Intent altIntent = new Intent(android.content.Intent.ACTION_VIEW);
                Uri rawuri = Uri.fromFile(tempFile);
                altIntent.setDataAndType(rawuri, mimeType);
                afterDecrypt(newIntent, altIntent);
            }
        }
    }.execute(encryptedFile);
}

From source file:at.bitfire.davdroid.ui.DebugInfoActivity.java

public void onShare(MenuItem item) {
    if (!TextUtils.isEmpty(report)) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_SUBJECT,
                getString(R.string.app_name) + " " + BuildConfig.VERSION_NAME + " debug info");

        // since Android 4.1, FileProvider permissions are handled in a useful way (using ClipData)
        boolean asAttachment = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;

        if (asAttachment)
            try {
                File debugInfoDir = new File(getCacheDir(), "debug-info");
                debugInfoDir.mkdir();/*from   ww  w. ja  va2  s .  c  o m*/

                reportFile = new File(debugInfoDir, "debug.txt");
                App.log.fine("Writing debug info to " + reportFile.getAbsolutePath());
                FileWriter writer = new FileWriter(reportFile);
                writer.write(report);
                writer.close();

                sendIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,
                        getString(R.string.authority_log_provider), reportFile));
                sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            } catch (IOException e) {
                // creating an attachment failed, so send it inline
                asAttachment = false;

                StringBuilder builder = new StringBuilder();
                builder.append("Couldn't write debug info file:\n").append(ExceptionUtils.getStackTrace(e))
                        .append("\n\n").append(report);
                report = builder.toString();
            }

        if (!asAttachment)
            sendIntent.putExtra(Intent.EXTRA_TEXT, report);

        startActivity(Intent.createChooser(sendIntent, null));
    }
}

From source file:com.digigene.autoupdate.presenter.DownloadDialogPresenterImpl.java

private void doWhenDownloadIsFinishedInForcedMode(String fileName) {
    File directory = context.getExternalFilesDir(null);
    File file = new File(directory, fileName);
    Uri fileUri = Uri.fromFile(file);//w  w  w.j av a  2s. c om
    if (Build.VERSION.SDK_INT >= 24) {
        fileUri = FileProvider.getUriForFile(context, context.getPackageName(), file);
    }
    Intent intent = new Intent(Intent.ACTION_VIEW, fileUri);
    intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
    intent.setDataAndType(fileUri, "application/vnd.android" + ".package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(intent);
    activity.finish();
}

From source file:com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock5ViewHolder.java

private void startShareIntent(String fileUrl) {
    File file = null;/*from w w w .ja v a2 s .  c om*/
    try {
        file = mFileManager.getFile(fileUrl);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (file == null) {
        fileNotFoundToast();
        return;
    }

    Uri fileUri = FileProvider.getUriForFile(mFragment.getContext(), Config.AUTHORITY, file);
    Intent shareIntent = ShareCompat.IntentBuilder.from(mFragment.getActivity())
            .setType(mFragment.getContext().getContentResolver().getType(fileUri)).setStream(fileUri)
            .getIntent();
    shareIntent.setData(fileUri);
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    mFragment.getActivity().startActivity(shareIntent);
}

From source file:com.commonsware.android.camcon.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CONTENT_REQUEST) {
        if (resultCode == RESULT_OK) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            Uri outputUri = FileProvider.getUriForFile(this, AUTHORITY, output);

            i.setDataAndType(outputUri, "image/jpeg");
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                startActivity(i);//from w  w  w  .  java  2s.  c o m
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, R.string.msg_no_viewer, Toast.LENGTH_LONG).show();
            }

            finish();
        }
    }
}

From source file:com.android.settings.SettingsLicenseActivity.java

private void showHtmlFromUri(Uri uri) {
    // Kick off external viewer due to WebView security restrictions; we
    // carefully point it at HTMLViewer, since it offers to decompress
    // before viewing.
    final Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(uri, "text/html");
    intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_license_activity_title));
    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }//  w w w .  j av a 2  s .c o  m
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setPackage("com.android.htmlviewer");

    try {
        startActivity(intent);
        finish();
    } catch (ActivityNotFoundException e) {
        Log.e(TAG, "Failed to find viewer", e);
        showErrorAndFinish();
    }
}

From source file:org.jraf.android.downloadandshareimage.app.downloadandshare.DownloadAndShareActivity.java

private void startDownload() {
    new TaskFragment(new Task<DownloadAndShareActivity>() {
        public File mFile;
        public Error mError;

        @Override// w  w  w  . j a va 2s .  co  m
        protected void doInBackground() throws Throwable {
            DownloadAndShareActivity a = getActivity();
            try {
                mFile = getTemporaryFile();

                // Start downloading now (blocking)
                HttpUtil.get(a.mUrl).receive(mFile);

                // Check for a valid image
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(mFile.getPath(), opts);
                Log.d("width=" + opts.outWidth + " height=" + opts.outHeight);
                if (opts.outWidth == -1) {
                    mFile = null;
                    mError = Error.NOT_AN_IMAGE;
                }
            } catch (IOException e) {
                Log.w("Could not download " + mUrl, e);
                mFile = null;
                mError = Error.DOWNLOAD;
            }
        }

        @Override
        protected void onPostExecuteOk() {
            DownloadAndShareActivity a = getActivity();
            if (mFile == null) {
                switch (mError) {
                case DOWNLOAD:
                    Toast.makeText(a, R.string.error_download, Toast.LENGTH_LONG).show();
                    break;

                case NOT_AN_IMAGE:
                    Toast.makeText(a, R.string.error_notAnImage, Toast.LENGTH_LONG).show();
                    break;
                }

                a.finish();
                return;
            }

            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFile));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // Here we hardcode to jpeg, which is OK because other apps will filter on "image/*"
            intent.setType("image/jpeg");

            a.startActivity(Intent.createChooser(intent, null));
            a.finish();
        }
    }.toastFail(R.string.error_download)).execute(getSupportFragmentManager());
}

From source file:com.android.contacts.util.ContactPhotoUtils.java

/**
 * Adds common extras to gallery intents.
 *
 * @param intent The intent to add extras to.
 * @param photoUri The uri of the file to save the image to.
 *//*from   w  ww . jav  a2 s.  c  o m*/
public static void addPhotoPickerExtras(Intent intent, Uri photoUri) {
    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setClipData(ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, photoUri));
}

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 {//  ww w  .  j a  v a 2 s .c  o  m
        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);
    }
}