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.alibaba.weex.update.UpdateService.java

private void handleActionUpdate(String url) {
    manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(CheckForUpdateUtil.getStringRes(R.string.update_downloading))
            .setContentText(CheckForUpdateUtil.getStringRes(R.string.update_progress) + " 0%")
            .setTicker(CheckForUpdateUtil.getStringRes(R.string.update_downloading))
            .setWhen(System.currentTimeMillis()).setPriority(Notification.PRIORITY_DEFAULT)
            .setSmallIcon(R.mipmap.ic_launcher).setProgress(100, 0, false);
    manager.notify(NOTIFY_ID, builder.build());

    WXLogUtils.e("Update", "start download");
    Downloader.download(url,//from   w w  w .j  a va2s  .c  o  m
            new Downloader.DownloadCallback(getCacheDir().getAbsolutePath(), "playground.apk") {

                @Override
                public void onProgress(float progress) {
                    if (progress * 100 - progress >= 1) {
                        int p = (int) (progress * 100);
                        builder.setContentText(
                                CheckForUpdateUtil.getStringRes(R.string.update_progress) + p + "%");
                        builder.setProgress(100, p, false);
                        manager.notify(NOTIFY_ID, builder.build());
                        WXLogUtils.d("Update", "progress:" + p);
                    }
                }

                @Override
                public void onResponse(File file) {
                    WXLogUtils.d("Update", "success: " + file.getAbsolutePath());
                    manager.cancel(NOTIFY_ID);
                    Uri uri = Uri.fromFile(file);
                    Intent installIntent = new Intent(Intent.ACTION_VIEW);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        Uri contentUri = FileProvider.getUriForFile(WXEnvironment.getApplication(),
                                BuildConfig.APPLICATION_ID + ".fileprovider", file);
                        installIntent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    }
                    startActivity(installIntent);
                }

                @Override
                public void onError(final Exception e) {
                    WXSDKManager.getInstance().getWXRenderManager().postOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(UpdateService.this, "Failed to update:" + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }, 0);
                }
            });
}

From source file:com.ez.gallery.PhotoBaseActivity.java

/**
 * ?/*www.ja  va2  s .  c o m*/
 */
protected void takePhotoAction() {
    if (!DeviceUtils.existSDCard()) {
        String errormsg = getString(R.string.empty_sdcard);
        toast(errormsg);
        if (mTakePhotoAction) {
            resultFailure(errormsg, true);
        }
        return;
    }

    File takePhotoFolder;
    if (StringUtils.isEmpty(mPhotoTargetFolder)) {
        takePhotoFolder = Picseler.getCoreConfig().getTakePhotoFolder();
    } else {
        takePhotoFolder = new File(mPhotoTargetFolder);
    }
    boolean suc = FileUtils.mkdirs(takePhotoFolder);
    File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");

    if (suc) {
        mTakePhotoUri = Uri.fromFile(toFile);
        Uri uri = FileProvider.getUriForFile(this, Picseler.getCoreConfig().getFileProvider(), toFile);//FileProvidercontentUri
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(captureIntent, Picseler.TAKE_REQUEST_CODE);
    } else {
        takePhotoFailure();
    }
}

From source file:org.fdroid.fdroid.installer.DefaultInstallerActivity.java

@SuppressLint("InlinedApi")
private void installPackage(Uri uri) {
    if (uri == null) {
        throw new RuntimeException("Set the data uri to point to an apk location!");
    }/*w  w  w.  j a  v  a  2 s .  com*/
    // https://code.google.com/p/android/issues/detail?id=205827
    if ((Build.VERSION.SDK_INT < 24) && (!uri.getScheme().equals("file"))) {
        throw new RuntimeException("PackageInstaller < Android N only supports file scheme!");
    }
    if ((Build.VERSION.SDK_INT >= 24) && (!uri.getScheme().equals("content"))) {
        throw new RuntimeException("PackageInstaller >= Android N only supports content scheme!");
    }

    Intent intent = new Intent();

    // Note regarding EXTRA_NOT_UNKNOWN_SOURCE:
    // works only when being installed as system-app
    // https://code.google.com/p/android/issues/detail?id=42253

    if (Build.VERSION.SDK_INT < 14) {
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
    } else if (Build.VERSION.SDK_INT < 16) {
        intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
        intent.setData(uri);
        intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
        intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
        intent.putExtra(Intent.EXTRA_ALLOW_REPLACE, true);
    } else if (Build.VERSION.SDK_INT < 24) {
        intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
        intent.setData(uri);
        intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
        intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
    } else { // Android N
        intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
        intent.setData(uri);
        // grant READ permission for this content Uri
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
        intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
    }

    try {
        startActivityForResult(intent, REQUEST_CODE_INSTALL);
    } catch (ActivityNotFoundException e) {
        Log.e(TAG, "ActivityNotFoundException", e);
        installer.sendBroadcastInstall(downloadUri, Installer.ACTION_INSTALL_INTERRUPTED,
                "This Android rom does not support ACTION_INSTALL_PACKAGE!");
        finish();
    }
    installer.sendBroadcastInstall(downloadUri, Installer.ACTION_INSTALL_STARTED);
}

From source file:com.example.android.commitcontent.app.ImageKeyboard.java

private void doCommitContent(@NonNull String description, @NonNull String mimeType, @NonNull File file) {
    final EditorInfo editorInfo = getCurrentInputEditorInfo();

    // Validate packageName again just in case.
    if (!validatePackageName(editorInfo)) {
        return;/*from w  ww  . j a  v a  2 s .  c  o m*/
    }

    final Uri contentUri = FileProvider.getUriForFile(this, AUTHORITY, file);

    // As you as an IME author are most likely to have to implement your own content provider
    // to support CommitContent API, it is important to have a clear spec about what
    // applications are going to be allowed to access the content that your are going to share.
    final int flag;
    if (Build.VERSION.SDK_INT >= 25) {
        // On API 25 and later devices, as an analogy of Intent.FLAG_GRANT_READ_URI_PERMISSION,
        // you can specify InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION to give
        // a temporary read access to the recipient application without exporting your content
        // provider.
        flag = InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION;
    } else {
        // On API 24 and prior devices, we cannot rely on
        // InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION. You as an IME author
        // need to decide what access control is needed (or not needed) for content URIs that
        // you are going to expose. This sample uses Context.grantUriPermission(), but you can
        // implement your own mechanism that satisfies your own requirements.
        flag = 0;
        try {
            // TODO: Use revokeUriPermission to revoke as needed.
            grantUriPermission(editorInfo.packageName, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } catch (Exception e) {
            Log.e(TAG, "grantUriPermission failed packageName=" + editorInfo.packageName + " contentUri="
                    + contentUri, e);
        }
    }

    final InputContentInfoCompat inputContentInfoCompat = new InputContentInfoCompat(contentUri,
            new ClipDescription(description, new String[] { mimeType }), null /* linkUrl */);
    InputConnectionCompat.commitContent(getCurrentInputConnection(), getCurrentInputEditorInfo(),
            inputContentInfoCompat, flag, null);
}

From source file:com.nextgis.mobile.util.ApkDownloader.java

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);

    mProgress.dismiss();//from www .jav a 2 s .  co m

    if (result == null) {
        Intent install = new Intent();
        install.setAction(Intent.ACTION_VIEW);
        File apk = new File(mApkPath);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(mActivity, "com.keenfin.easypicker.provider", apk);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else
            uri = Uri.fromFile(apk);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        mActivity.startActivity(install);
    } else
        Toast.makeText(mActivity, result, Toast.LENGTH_LONG).show(); // show some info

    ControlHelper.unlockScreenOrientation(mActivity);
    if (mAutoClose)
        mActivity.finish();
}

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

private void startShareIntent(String fileUrl) {
    File file = null;/*www  . j  a v  a 2 s  .  com*/
    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 intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(fileUri, mFragment.getContext().getContentResolver().getType(fileUri));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

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

From source file:net.coscolla.comicstrip.ui.detail.DetailStripActivity.java

@NonNull
private Intent getShareIntent() {
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);

    shareIntent.putExtra(Intent.EXTRA_TEXT,
            "See this strip: " + currentStrip.title + " from " + currentStrip.url + " via ComicStrip App");
    shareIntent.setType("text/plain");

    /*/*from   ww w. j  av a  2s  .c  o  m*/
    Not working properly, removed for release
    String imagePath = useCase.getShareImagePath(currentStrip);
    if(imagePath != null) {
      Uri imageUri = Uri.parse(imagePath);
      shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
      shareIntent.setType("image/png");
    }
    */
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    return shareIntent;
}

From source file:com.commonsware.android.tte.DocumentStorageService.java

private void save(Uri document, String text, boolean isClosing) {
    boolean isContent = ContentResolver.SCHEME_CONTENT.equals(document.getScheme());

    try {//  www.ja  va 2 s  .  co  m
        OutputStream os = getContentResolver().openOutputStream(document, "w");
        OutputStreamWriter osw = new OutputStreamWriter(os);

        try {
            osw.write(text);
            osw.flush();

            if (isClosing && isContent) {
                int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

                getContentResolver().releasePersistableUriPermission(document, perms);
            }

            EventBus.getDefault().post(new DocumentSavedEvent(document));
        } finally {
            osw.close();
        }
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception saving " + document.toString(), e);
        EventBus.getDefault().post(new DocumentSaveErrorEvent(document, e));
    }
}

From source file:de.grundid.plusrad.map.ShowMap.java

public void performExport(String geoJsonData) {
    try {//from  w w w .j a  v  a2 s .  co m
        File exportFile = createTrackFile(geoJsonData);
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        Uri shareUri = FileProvider.getUriForFile(this, "de.grundid.plusrad.fileprovider", exportFile);
        shareIntent.setData(shareUri);
        shareIntent.putExtra(Intent.EXTRA_STREAM, shareUri);
        shareIntent.setType("text/comma_separated_values/csv");
        shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, "Track exportieren"));
    } catch (IOException e) {
        e.printStackTrace();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Fehler").setMessage("Fehler beim Exportieren des Tracks. [" + e.getMessage() + "]");
        builder.setPositiveButton("OK", null).show();
    }
}

From source file:com.mediatek.mms.util.VCardUtils.java

public static void importVCard(Context context, FileAttachmentModel attach) {
    MessageUtils.deleteAllSharedFiles(context, ".vcf");
    MmsLog.d(TAG, "importVCard, file uri: " + attach.getUri());
    final File tempVCard = MessageUtils.createTempFileExposed(context, attach.getUri(), attach.getSrc());
    if (tempVCard == null || !tempVCard.exists() || tempVCard.length() <= 0) {
        MmsLog.e(TAG, "importVCard, file is not exists or empty " + tempVCard);
        return;// www  .  j  a  va  2  s  .com
    }

    Uri vCardUri = FileProvider.getUriForFile(context, MMS_FILE_PROVIDER_AUTHORITIES, tempVCard);
    MmsLog.i(TAG, "importVCard, vCard uri: " + vCardUri);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(vCardUri, attach.getContentType().toLowerCase());
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(intent);
}