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.keepassdroid.fileselect.FileSelectActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    fillData();//  w  w w. jav  a2  s . co  m

    String filename = null;
    if (requestCode == FILE_BROWSE && resultCode == RESULT_OK) {
        filename = data.getDataString();
        if (filename != null) {
            if (filename.startsWith("file://")) {
                filename = filename.substring(7);
            }

            filename = URLDecoder.decode(filename);
        }

    } else if ((requestCode == GET_CONTENT || requestCode == OPEN_DOC) && resultCode == RESULT_OK) {
        if (data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                if (StorageAF.useStorageFramework(this)) {
                    try {
                        // try to persist read and write permissions
                        ContentResolver resolver = getContentResolver();
                        ContentResolverCompat.takePersistableUriPermission(resolver, uri,
                                Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        ContentResolverCompat.takePersistableUriPermission(resolver, uri,
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    } catch (Exception e) {
                        // nop
                    }
                }
                if (requestCode == GET_CONTENT) {
                    uri = UriUtil.translate(this, uri);
                }
                filename = uri.toString();
            }
        }
    }

    if (filename != null) {
        EditText fn = (EditText) findViewById(R.id.file_filename);
        fn.setText(filename);
    }
}

From source file:com.apptentive.android.sdk.module.engagement.interaction.fragment.MessageCenterFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case Constants.REQUEST_CODE_CLOSE_COMPOSING_CONFIRMATION: {
            onCancelComposing();//from w w w. j a va  2  s . c  o m
            break;
        }
        case Constants.REQUEST_CODE_PHOTO_FROM_SYSTEM_PICKER: {
            if (data == null) {
                ApptentiveLog.d("no image is picked");
                return;
            }
            imagePickerStillOpen = false;
            Uri uri;
            Activity hostingActivity = hostingActivityRef.get();
            //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;
                if (hostingActivity != null) {
                    hostingActivity.getContentResolver().takePersistableUriPermission(uri, takeFlags);
                }
            }

            EngagementModule.engageInternal(getActivity(), interaction,
                    MessageCenterInteraction.EVENT_NAME_ATTACH);

            String originalPath = Util.getRealFilePathFromUri(hostingActivity, 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(hostingActivity, uri);
                Uri fileUri = Uri.fromFile(new File(originalPath));
                File cacheDir = Util.getDiskCacheDir(hostingActivity);
                addAttachmentsToComposer(new ImageItem(originalPath,
                        Util.generateCacheFileFullPath(fileUri, cacheDir, creation_time),
                        Util.getMimeTypeFromUri(hostingActivity, 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(hostingActivity);
                String cachedFileName = Util.generateCacheFileFullPath(uri, cacheDir, 0);
                addAttachmentsToComposer(new ImageItem(uri.toString(), cachedFileName,
                        Util.getMimeTypeFromUri(hostingActivity, uri), 0));
            }

            break;
        }
        default:
            break;
        }
    }
}

From source file:com.orpheusdroid.screenrecorder.adapter.VideoRecyclerAdapter.java

/**
 * Share the videos selected/*w  w w .  ja v a  2  s .  c o m*/
 *
 * @param position Integer value representing the position of the video to be shared
 * @see #shareVideos(ArrayList positions)
 */
private void shareVideo(int position) {
    Uri fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider",
            videos.get(position).getFile());

    Intent Shareintent = new Intent().setAction(Intent.ACTION_SEND).setType("video/*")
            .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION).putExtra(Intent.EXTRA_STREAM, fileUri);
    context.startActivity(
            Intent.createChooser(Shareintent, context.getString(R.string.share_intent_notification_title)));
}

From source file:de.stadtrallye.rallyesoft.services.UploadService.java

@TargetApi(19)
private void persistUriPermissionApi19(Uri uri) {
    getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}

From source file:be.ppareit.swiftp.gui.PreferenceFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (requestCode == ACTION_OPEN_DOCUMENT_TREE && resultCode == Activity.RESULT_OK) {
        Uri treeUri = resultData.getData();
        String path = treeUri.getPath();

        final CheckBoxPreference writeExternalStorage_pref = findPref("writeExternalStorage");
        if (!":".equals(path.substring(path.length() - 1)) || path.contains("primary")) {
            writeExternalStorage_pref.setChecked(false);
        } else {//from w  w w.  j a  v a2s.  co  m
            FsSettings.setExternalStorageUri(treeUri.toString());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getActivity().getContentResolver().takePersistableUriPermission(treeUri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            writeExternalStorage_pref.setChecked(true);
        }
    }

}

From source file:org.wso2.iot.agent.api.ApplicationManager.java

/**
 * Installs an application to the device.
 *
 * @param fileUri - File URI should be passed in as a String.
 */// w  ww .ja  v  a 2  s .  c  om
private void startInstallerIntent(Uri fileUri) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
            && policyManager.isDeviceOwnerApp(Constants.AGENT_PACKAGE)) {
        Uri packageFileUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            packageFileUri = convertContentUriToFileUri(fileUri);
        } else {
            packageFileUri = fileUri;
        }
        installPackage(packageFileUri);
    } else {
        boolean isUnknownSourcesDisallowed = Preference.getBoolean(context,
                Constants.PreferenceFlag.DISALLOW_UNKNOWN_SOURCES);
        CommonUtils.allowUnknownSourcesForProfile(context, !isUnknownSourcesDisallowed);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent.setDataAndType(fileUri, resources.getString(R.string.application_mgr_mime));
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(intent);
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(fileUri, resources.getString(R.string.application_mgr_mime));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }
}

From source file:de.kaidev.vertretungsplanapp.MainActivity.java

@Override
public void downloadPostExecute(File result) {
    downloadClearUI();/*from  w w w  .  j  a v a  2  s .  co  m*/
    startActivity(new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            .setDataAndType(
                    FileProvider.getUriForFile(this, "de.kaidev.vertretungsplanapp.file_provider", result),
                    "application/vnd.android.package-archive")
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}

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

/**
 * Open file from OTG/* ww w  .  j av a 2  s .c  om*/
 */
public static void openunknown(DocumentFile f, Context c, boolean forcechooser, boolean useNewStack) {
    Intent chooserIntent = new Intent();
    chooserIntent.setAction(Intent.ACTION_VIEW);
    chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    String type = f.getType();
    if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
        chooserIntent.setDataAndType(f.getUri(), type);
        Intent activityIntent;
        if (forcechooser) {
            if (useNewStack)
                applyNewDocFlag(chooserIntent);
            activityIntent = Intent.createChooser(chooserIntent, c.getString(R.string.openwith));
        } else {
            activityIntent = chooserIntent;
            if (useNewStack)
                applyNewDocFlag(chooserIntent);
        }

        try {
            c.startActivity(activityIntent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c, useNewStack);
        }
    } else {
        openWith(f, c, useNewStack);
    }
}

From source file:org.mariotaku.gallery3d.app.ImageViewerGLActivity.java

private static Intent createShareIntent(final MediaItem mediaObject) {
    return new Intent(Intent.ACTION_SEND).setType("image/*")
            .putExtra(Intent.EXTRA_STREAM, mediaObject.getContentUri())
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}

From source file:org.messic.android.smartphone.activities.main.fragments.queue.PlayQueueFragment.java

private void shareAudio(PlayQueueSongViewHolder holder) {
    File songPath = null;/*from  w w  w.j a  v a 2s.  co  m*/
    try {
        if (holder.song.isDownloaded(config)) {
            String folderPath = holder.song.calculateExternalStorageFolder();
            String filePath = folderPath + "/" + holder.song.calculateExternalFilename();
            songPath = new File(filePath);
        } else {
            //we create the tmp file at the messic folder
            String tmpFile = UtilFile.getMessicOfflineFolderAbsolutePath() + "/.tmp";
            File outputDir = new File(tmpFile);
            outputDir.mkdirs();
            outputDir = new File(tmpFile + "/share.mp3");
            if (outputDir.exists())
                outputDir.delete();

            String sharePath = holder.song.getURL(config);
            URL url = new URL(sharePath);
            InputStream is = url.openStream();
            FileOutputStream fos = new FileOutputStream(outputDir);
            byte[] b = new byte[1024];
            int length;

            while ((length = is.read(b)) != -1) {
                fos.write(b, 0, length);
            }
            is.close();
            fos.close();
            songPath = outputDir;
        }

        Uri uriOld = Uri.parse(songPath.getAbsolutePath());

        Uri uri2 = MediaStore.Audio.Media.getContentUriForPath(songPath.getAbsolutePath());
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.TITLE, holder.song.getName());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
        values.put(MediaStore.MediaColumns.DATA, songPath.getAbsolutePath());
        values.put(MediaStore.Audio.Media.DATA, songPath.getAbsolutePath());
        values.put(MediaStore.Audio.Media.ARTIST, holder.song.getAlbum().getAuthor().getName());
        values.put(MediaStore.Audio.Media.ALBUM, holder.song.getAlbum().getName());
        values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
        values.put(MediaStore.Audio.Media.IS_ALARM, false);
        values.put(MediaStore.Audio.Media.IS_MUSIC, true);
        Uri newUri = getActivity().getContentResolver().insert(uri2, values);

        Intent share = new Intent(Intent.ACTION_SEND_MULTIPLE);
        share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        share.setType("audio/*");

        String shareBody = getString(R.string.share_song_text_start) + " \"" + holder.song.getName() + "\" "
                + getString(R.string.share_song_text_album) + " \"" + holder.song.getAlbum().getName() + "\""
                + getString(R.string.share_song_text_of) + "\"" + holder.song.getAlbum().getAuthor().getName()
                + "\"" + " (I <3 messic)";

        share.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
        share.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        //            ArrayList<Uri> uris = new ArrayList<>();
        //            uris.add(uri);
        //share.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        share.putExtra(Intent.EXTRA_STREAM, uriOld);

        startActivity(Intent.createChooser(share, getString(R.string.share_by)));
    } catch (IOException e) {
        e.printStackTrace();
    }
}