Java Code Examples for android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION

The following examples show how to use android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: keemob   File: FileChooser.java    License: MIT License 6 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if (resultCode != Activity.RESULT_OK) {
        return;
    }

    if (requestCode == CODE_CHOOSE_FILE) {
        Uri uri = intent.getData();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final int takeFlags = intent.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            cordova.getActivity().getContentResolver().takePersistableUriPermission(uri, takeFlags);
        }

        callbackContext.success(asFile(uri));
        callbackContext = null;
    }

    super.onActivityResult(requestCode, resultCode, intent);
}
 
Example 2
Source Project: android_9.0.0_r45   File: UriPermission.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return if mode changes should trigger persisting.
 */
boolean takePersistableModes(int modeFlags) {
    modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    if ((modeFlags & persistableModeFlags) != modeFlags) {
        Slog.w(TAG, "Requested flags 0x"
                + Integer.toHexString(modeFlags) + ", but only 0x"
                + Integer.toHexString(persistableModeFlags) + " are allowed");
        return false;
    }

    final int before = persistedModeFlags;
    persistedModeFlags |= (persistableModeFlags & modeFlags);

    if (persistedModeFlags != 0) {
        persistedCreateTime = System.currentTimeMillis();
    }

    updateModeFlags();
    return persistedModeFlags != before;
}
 
Example 3
private static int getCallingOrSelfUriPermissionModeFlags(Context context, Uri uri) {
    // TODO: move this to a direct AMS call
    int modeFlags = 0;
    if (context.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
            == PackageManager.PERMISSION_GRANTED) {
        modeFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION;
    }
    if (context.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            == PackageManager.PERMISSION_GRANTED) {
        modeFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
    }
    if (context.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION
            | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
            == PackageManager.PERMISSION_GRANTED) {
        modeFlags |= Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
    }
    return modeFlags;
}
 
Example 4
@Override
public int checkUriPermission(Uri uri, String readPermission,
        String writePermission, int pid, int uid, int modeFlags) {
    if (DEBUG) {
        Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
                + readPermission + " writePermission=" + writePermission
                + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
    }
    if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
        if (readPermission == null
                || checkPermission(readPermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
        if (writePermission == null
                || checkPermission(writePermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
            : PackageManager.PERMISSION_DENIED;
}
 
Example 5
@Override
public int checkUriPermission(Uri uri, String readPermission,
        String writePermission, int pid, int uid, int modeFlags) {
    if (DEBUG) {
        Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
                + readPermission + " writePermission=" + writePermission
                + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
    }
    if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
        if (readPermission == null
                || checkPermission(readPermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
        if (writePermission == null
                || checkPermission(writePermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
            : PackageManager.PERMISSION_DENIED;
}
 
Example 6
Source Project: android_9.0.0_r45   File: ContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int checkUriPermission(Uri uri, String readPermission,
        String writePermission, int pid, int uid, int modeFlags) {
    if (DEBUG) {
        Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
                + readPermission + " writePermission=" + writePermission
                + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
    }
    if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
        if (readPermission == null
                || checkPermission(readPermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
        if (writePermission == null
                || checkPermission(writePermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
            : PackageManager.PERMISSION_DENIED;
}
 
Example 7
@Override
public int checkUriPermission(Uri uri, String readPermission,
        String writePermission, int pid, int uid, int modeFlags) {
    if (DEBUG) {
        Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
                + readPermission + " writePermission=" + writePermission
                + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
    }
    if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
        if (readPermission == null
                || checkPermission(readPermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
        if (writePermission == null
                || checkPermission(writePermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
            : PackageManager.PERMISSION_DENIED;
}
 
Example 8
Source Project: android_9.0.0_r45   File: UriPermission.java    License: Apache License 2.0 6 votes vote down vote up
boolean releasePersistableModes(int modeFlags) {
    modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    final int before = persistedModeFlags;

    persistableModeFlags &= ~modeFlags;
    persistedModeFlags &= ~modeFlags;

    if (persistedModeFlags == 0) {
        persistedCreateTime = INVALID_TIME;
    }

    updateModeFlags();
    return persistedModeFlags != before;
}
 
Example 9
@Override
public int checkUriPermission(Uri uri, String readPermission,
        String writePermission, int pid, int uid, int modeFlags) {
    if (DEBUG) {
        Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
                + readPermission + " writePermission=" + writePermission
                + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
    }
    if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
        if (readPermission == null
                || checkPermission(readPermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
        if (writePermission == null
                || checkPermission(writePermission, pid, uid)
                == PackageManager.PERMISSION_GRANTED) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }
    return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
            : PackageManager.PERMISSION_DENIED;
}
 
Example 10
private String uriModeFlagToString(int uriModeFlags) {
    StringBuilder builder = new StringBuilder();
    if ((uriModeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
        builder.append("read and ");
    }
    if ((uriModeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
        builder.append("write and ");
    }
    if ((uriModeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) {
        builder.append("persistable and ");
    }
    if ((uriModeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) {
        builder.append("prefix and ");
    }

    if (builder.length() > 5) {
        builder.setLength(builder.length() - 5);
        return builder.toString();
    } else {
        throw new IllegalArgumentException("Unknown permission mode flags: " + uriModeFlags);
    }
}
 
Example 11
Source Project: openlauncher   File: ShareUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Request edit of image (by image editor/viewer - for example to crop image)
 *
 * @param file File that should be edited
 */
public void requestPictureEdit(final File file) {
    Uri uri = getUriByFileProviderAuthority(file);
    int flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION;

    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setDataAndType(uri, "image/*");
    intent.addFlags(flags);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    intent.putExtra(EXTRA_FILEPATH, file.getAbsolutePath());

    for (ResolveInfo resolveInfo : _context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)) {
        String packageName = resolveInfo.activityInfo.packageName;
        _context.grantUriPermission(packageName, uri, flags);
    }
    _context.startActivity(Intent.createChooser(intent, null));
}
 
Example 12
Source Project: ImagePicker   File: DocumentPicker.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Uri onResult(Intent data) {
    Uri imageUri = data.getData();
    if (imageUri == null) {
        return null;
    }
    if (isUpAPI19()) {
        final int takeFlags = data.getFlags()
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // Check for the freshest data.
        mPickerConfig.getActivity().getContentResolver().takePersistableUriPermission(imageUri, takeFlags);
    }

    String content = "DocumentPicker pick data:" + imageUri.toString();
    try {
        // 取出文件真实路径
        String path = MediaUtils.getMediaRealPathFromUri(mPickerConfig.getActivity(), data.getData());
        if (path == null) {
            content += "\npath=null";
            return null;
        } else {
            content += "\npath=" + path;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return ImagePickerFileProvider.getUriForFile(mPickerConfig.getActivity(), new File(path));
            }
            return Uri.fromFile(new File(path));
        }
    } finally {
        LogUtils.d(content);
    }
}
 
Example 13
private void onSelectBackupsLocationResult(int resultCode, Intent data) {
    Uri uri = data.getData();
    if (resultCode != Activity.RESULT_OK || uri == null) {
        return;
    }

    int flags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    getContext().getContentResolver().takePersistableUriPermission(data.getData(), flags);

    _prefs.setBackupsLocation(uri);
    _prefs.setIsBackupsEnabled(true);
    _prefs.setBackupsError(null);
    _backupsLocationPreference.setSummary(String.format("%s: %s", getString(R.string.pref_backups_location_summary), Uri.decode(uri.toString())));
    updateBackupPreference();
}
 
Example 14
Source Project: FitAndroid7   File: FileProvider7.java    License: Apache License 2.0 5 votes vote down vote up
public 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;
        }
        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);
        }
    }
 
Example 15
Source Project: android_9.0.0_r45   File: UriPermission.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initialize persisted modes as read from file. This doesn't issue any
 * global or owner grants.
 */
void initPersistedModes(int modeFlags, long createdTime) {
    modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    persistableModeFlags = modeFlags;
    persistedModeFlags = modeFlags;
    persistedCreateTime = createdTime;

    updateModeFlags();
}
 
Example 16
public static boolean checkGrantFlags(int grantFlags) {
    return (grantFlags & (Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            |Intent.FLAG_GRANT_READ_URI_PERMISSION)) != 0;
}
 
Example 17
Source Project: belvedere   File: MediaSource.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Internal helper method to create an {@link MediaIntent} for opening
 * an installed camera app.
 *
 * @param context A valid application {@link Context}
 * @return An {@link MediaIntent} or null if this action isn't supported by
 *      the system.
 */
private Pair<MediaIntent, MediaResult> pickImageFromCameraInternal(Context context, int requestCode){

    final File imagePath = storage.getFileForCamera(context);

    if (imagePath == null){
        L.w(Belvedere.LOG_TAG, "Camera Intent: Image path is null. There's something wrong with the storage.");
        return null;
    }

    final Uri uriForFile = storage.getFileProviderUri(context, imagePath);

    if (uriForFile == null) {
        L.w(Belvedere.LOG_TAG, "Camera Intent: Uri to file is null. There's something wrong with the storage or FileProvider configuration.");
        return null;
    }

    L.d(Belvedere.LOG_TAG, String.format(Locale.US, "Camera Intent: Request Id: %s - File: %s - Uri: %s", requestCode, imagePath, uriForFile));

    final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uriForFile);
    int permission = Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION;
    storage.grantPermissionsForUri(context, intent, uriForFile, permission);

    /*
        https://code.google.com/p/android/issues/detail?id=188073&q=label%3APriority-Medium&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&start=100
     */
    final boolean cameraPermissionInManifestButNoGranted =
            PermissionUtil.hasPermissionInManifest(context, Manifest.permission.CAMERA) &&
            !PermissionUtil.isPermissionGranted(context, Manifest.permission.CAMERA);

    final MediaResult r = Storage.getMediaResultForUri(context, uriForFile);
    final MediaResult belvedereResult = new MediaResult(imagePath, uriForFile, uriForFile, imagePath.getName(), r.getMimeType(), r.getSize(), r.getWidth(), r.getHeight());
    final MediaIntent mediaIntent = new MediaIntent(
            requestCode,
            intent,
            cameraPermissionInManifestButNoGranted ? Manifest.permission.CAMERA : null,
            true,
            MediaIntent.TARGET_CAMERA
    );

    return new Pair<>(mediaIntent, belvedereResult);
}
 
Example 18
/**
 * After triggering the Storage Access Framework, ensure that folder is really writable. Set preferences
 * accordingly.
 *
 * @param requestCode The integer request code originally supplied to startActivityForResult(), allowing you to identify who
 *                    this result came from.
 * @param resultCode  The integer result code returned by the child activity through its setResult().
 * @param data        An Intent, which can return result data to the caller (various data can be attached to Intent
 *                    "extras").
 */
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private void onActivityResultLollipop(final int requestCode, final int resultCode, @NonNull final Intent data) {
	int preferenceKeyUri;
	int preferenceKeyFolder;
	String oldFolder;
	if (requestCode == REQUEST_CODE_STORAGE_ACCESS_PHOTOS) {
		preferenceKeyUri = R.string.key_internal_uri_extsdcard_photos;
		preferenceKeyFolder = R.string.key_folder_photos;
		oldFolder = mFolderPhotos;
	}
	else if (requestCode == REQUEST_CODE_STORAGE_ACCESS_INPUT) {
		preferenceKeyUri = R.string.key_internal_uri_extsdcard_input;
		preferenceKeyFolder = R.string.key_folder_input;
		oldFolder = mFolderInput;
	}
	else {
		return;
	}

	Uri oldUri = PreferenceUtil.getSharedPreferenceUri(preferenceKeyUri);
	if (oldUri == null) {
		// Backward compatibility to the version where only the base key existed
		oldUri = PreferenceUtil.getSharedPreferenceUri(R.string.key_internal_uri_extsdcard_photos);
	}
	Uri treeUri = null;

	if (resultCode == Activity.RESULT_OK) {
		// Get Uri from Storage Access Framework.
		treeUri = data.getData();
		// Persist URI - this is required for verification of writability.
		PreferenceUtil.setSharedPreferenceUri(preferenceKeyUri, treeUri);
	}

	// If not confirmed SAF, or if still not writable, then revert settings.
	if (resultCode != Activity.RESULT_OK || !FileUtil.isWritableNormalOrSaf(mCurrentFolder)) {
		DialogUtil.displayError(getActivity(), R.string.message_dialog_cannot_write_to_folder_saf, false,
				mCurrentFolder);

		PreferenceUtil.setSharedPreferenceString(preferenceKeyFolder, oldFolder);
		findPreference(getString(preferenceKeyFolder)).setSummary(oldFolder);

		mCurrentFolder = null;
		PreferenceUtil.setSharedPreferenceUri(preferenceKeyUri, oldUri);
		return;
	}

	// After confirmation, update stored value of folder.
	if (preferenceKeyFolder == R.string.key_folder_photos) {
		mFolderPhotos = mCurrentFolder.getAbsolutePath();
	}
	if (preferenceKeyFolder == R.string.key_folder_input) {
		mFolderInput = mCurrentFolder.getAbsolutePath();
	}
	PreferenceUtil.setSharedPreferenceString(preferenceKeyFolder, mCurrentFolder.getAbsolutePath());
	findPreference(getString(preferenceKeyFolder)).setSummary(mCurrentFolder.getAbsolutePath());

	// Persist access permissions.
	final int takeFlags = data.getFlags()
			& (Intent.FLAG_GRANT_READ_URI_PERMISSION
			| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
	// noinspection ResourceType
	getActivity().getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
}
 
Example 19
Source Project: belvedere   File: Belvedere.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Revoke {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} that were
 * previously granted by {@link #grantPermissionsForUri(Intent, Uri)}.
 *
 * @param uri An {@link Uri}
 */
public void revokePermissionsForUri(@NonNull Uri uri) {
    L.d(LOG_TAG, String.format(Locale.US, "Revoke Permission - Uri: %s", uri));
    int permissions = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
    storage.revokePermissionsFromUri(context, uri, permissions);
}
 
Example 20
Source Project: belvedere   File: Belvedere.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Grant all Apps that are resolvable through the provided {@link Intent} {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}.
 *
 * @param intent An {@link Intent}
 * @param uri    An {@link Uri}
 */
public void grantPermissionsForUri(@NonNull Intent intent, @NonNull Uri uri) {
    L.d(LOG_TAG, String.format(Locale.US, "Grant Permission - Intent: %s - Uri: %s", intent, uri));
    int permissions = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
    storage.grantPermissionsForUri(context, intent, uri, permissions);
}