下面列出了android.content.Context#grantUriPermission ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Implementation is provided by the parent class. Can be overridden to
* provide additional functionality, but subclasses <em>must</em> always
* call the superclass. If the superclass returns {@code null}, the subclass
* may implement custom behavior.
* <p>
* This is typically used to resolve a subtree URI into a concrete document
* reference, issuing a narrower single-document URI permission grant along
* the way.
*
* @see android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, String)
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public Uri canonicalize(Uri uri) {
final Context context = getContext();
switch (mMatcher.match(uri)) {
case MATCH_DOCUMENT_TREE:
enforceTree(uri);
final Uri narrowUri = buildDocumentUri(uri.getAuthority(), getDocumentId(uri));
// Caller may only have prefix grant, so extend them a grant to
// the narrow URI.
final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context, uri);
if(Utils.hasKitKat()) {
context.grantUriPermission(getCallingPackage(), narrowUri, modeFlags);
}
return narrowUri;
}
return null;
}
/**
* Implementation is provided by the parent class. Can be overridden to
* provide additional functionality, but subclasses <em>must</em> always
* call the superclass. If the superclass returns {@code null}, the subclass
* may implement custom behavior.
* <p>
* This is typically used to resolve a subtree URI into a concrete document
* reference, issuing a narrower single-document URI permission grant along
* the way.
*
* @see android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, String)
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public Uri canonicalize(Uri uri) {
final Context context = getContext();
switch (mMatcher.match(uri)) {
case MATCH_DOCUMENT_TREE:
enforceTree(uri);
final Uri narrowUri = buildDocumentUri(uri.getAuthority(), getDocumentId(uri));
// Caller may only have prefix grant, so extend them a grant to
// the narrow URI.
final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context, uri);
if(Utils.hasKitKat()) {
context.grantUriPermission(getCallingPackage(), narrowUri, modeFlags);
}
return narrowUri;
}
return null;
}
/**
* Implementation is provided by the parent class. Can be overridden to
* provide additional functionality, but subclasses <em>must</em> always
* call the superclass. If the superclass returns {@code null}, the subclass
* may implement custom behavior.
* <p>
* This is typically used to resolve a subtree URI into a concrete document
* reference, issuing a narrower single-document URI permission grant along
* the way.
*
* @see android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, String)
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public Uri canonicalize(Uri uri) {
final Context context = getContext();
switch (mMatcher.match(uri)) {
case MATCH_DOCUMENT_TREE:
enforceTree(uri);
final Uri narrowUri = buildDocumentUri(uri.getAuthority(), getDocumentId(uri));
// Caller may only have prefix grant, so extend them a grant to
// the narrow URI.
final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context, uri);
if(Utils.hasKitKat()) {
context.grantUriPermission(getCallingPackage(), narrowUri, modeFlags);
}
return narrowUri;
}
return null;
}
public static void sendImage(Context context, Drawable drawable, String text){
context=context.getApplicationContext();
try {
File tempFile=File.createTempFile("toSend",".jpg");
tempFile.deleteOnExit();
Bitmap image=drawableToBitmap(drawable);
if(image==null)return;
saveImage(image,tempFile);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
if(text!=null)shareIntent.putExtra(Intent.EXTRA_TEXT, text);
Uri x= FileProvider.getUriForFile(context,context.getPackageName() + ".provider",tempFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, x);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(shareIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, x, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
shareIntent=Intent.createChooser(shareIntent, context.getString(R.string.share_with));
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(shareIntent);
} catch (IOException e) {
e.printStackTrace();
}
}
public void dispatchCaptureIntent(Context context, int requestCode) {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (captureIntent.resolveActivity(context.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
mCurrentPhotoPath = photoFile.getAbsolutePath();
mCurrentPhotoUri = FileProvider.getUriForFile(mContext.get(),
mCaptureStrategy.authority, photoFile);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoUri);
captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
List<ResolveInfo> resInfoList = context.getPackageManager()
.queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, mCurrentPhotoUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (mFragment != null) {
mFragment.get().startActivityForResult(captureIntent, requestCode);
} else {
mContext.get().startActivityForResult(captureIntent, requestCode);
}
}
}
}
public static void grantAppPermission(Context context, Intent intent, Uri fileUri) {
List<ResolveInfo> resolvedIntentActivities = context.getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolvedIntentInfo : resolvedIntentActivities) {
String packageName = resolvedIntentInfo.activityInfo.packageName;
context.grantUriPermission(packageName, fileUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
public void dispatchCaptureIntent(Context context, int requestCode) {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (captureIntent.resolveActivity(context.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
mCurrentPhotoPath = photoFile.getAbsolutePath();
mCurrentPhotoUri = FileProvider.getUriForFile(mContext.get(),
mCaptureStrategy.authority, photoFile);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoUri);
captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
List<ResolveInfo> resInfoList = context.getPackageManager()
.queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, mCurrentPhotoUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (mFragment != null) {
mFragment.get().startActivityForResult(captureIntent, requestCode);
} else {
mContext.get().startActivityForResult(captureIntent, requestCode);
}
}
}
}
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);
}
}
public void dispatchCaptureIntent(Context context, int requestCode) {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (captureIntent.resolveActivity(context.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
mCurrentPhotoPath = photoFile.getAbsolutePath();
mCurrentPhotoUri = FileProvider.getUriForFile(mContext.get(),
mCaptureStrategy.authority, photoFile);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoUri);
captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
List<ResolveInfo> resInfoList = context.getPackageManager()
.queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, mCurrentPhotoUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (mFragment != null) {
mFragment.get().startActivityForResult(captureIntent, requestCode);
} else {
mContext.get().startActivityForResult(captureIntent, requestCode);
}
}
}
}
public void dispatchCaptureIntent(Context context, int requestCode) {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (captureIntent.resolveActivity(context.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
mCurrentPhotoPath = photoFile.getAbsolutePath();
mCurrentPhotoUri = FileProvider.getUriForFile(mContext.get(),
mCaptureStrategy.authority, photoFile);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoUri);
captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
List<ResolveInfo> resInfoList = context.getPackageManager()
.queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, mCurrentPhotoUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (mFragment != null) {
mFragment.get().startActivityForResult(captureIntent, requestCode);
} else {
mContext.get().startActivityForResult(captureIntent, requestCode);
}
}
}
}
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);
}
}
/**
* Convert a raw resource to a file on the private storage
*
* @param ctx the application context
* @param resourceId the resource identifier
* @return the file or null if the process failed
*/
public static File oggToCacheAndGrant(@NonNull final Context ctx, final int resourceId, final String packageName) {
final String cachePath = getPrivateDirPath(ctx);
if (UtilsString.notNaked(cachePath)) {
final String name = ctx.getResources().getResourceEntryName(resourceId);
final File file = resourceToFile(ctx, resourceId, new File(cachePath + SOUND_EFFECT_DIR + name
+ "." + Constants.OGG_AUDIO_FILE_SUFFIX));
if (file != null) {
if (DEBUG) {
MyLog.i(CLS_NAME, "wavToCacheAndGrant file exists: " + file.exists());
MyLog.i(CLS_NAME, "wavToCacheAndGrant file path: " + file.getAbsolutePath());
}
final Uri contentUri = FileProvider.getUriForFile(ctx, FILE_PROVIDER, file);
ctx.grantUriPermission(packageName, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
return file;
} else {
if (DEBUG) {
MyLog.e(CLS_NAME, "wavToCacheAndGrant file null");
}
}
} else {
if (DEBUG) {
MyLog.e(CLS_NAME, "wavToCacheAndGrant failed to get any path");
}
}
return null;
}
/**
* Grant all Apps that are resolved through the provided {@link Intent} permissions to the file
* behind the provided {@link Uri}
*
* @param context A valid application {@link Context}
* @param intent An {@link Intent}
* @param uri An {@link Uri} to a file, managed by our {@link BelvedereFileProvider}
* @param permission Permission that should be granted to the Apps, opened by the provided Intent
*/
void grantPermissionsForUri(Context context, Intent intent, Uri uri, int permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
intent.addFlags(permission);
} else {
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, uri, permission);
}
}
}
/**
* Return a {@link Uri} for all install processes to install this package
* from. This supports APKs and all other supported files. It also
* supports all installation methods, e.g. default, privileged, etc.
* It can return either a {@code content://} or {@code file://} URI.
* <p>
* APKs need to be world readable, so that the Android system installer
* is able to read it. Saving it into external storage to send it to the
* installer have access is insecure, because apps with permission to write
* to the external storage can overwrite the app between F-Droid asking for
* it to be installed and the installer actually installing it.
*/
private static Uri getSafeUri(Context context, SanitizedFile tempFile, boolean useContentUri) {
if (useContentUri) {
Uri apkUri = getUriForFile(context, AUTHORITY, tempFile);
context.grantUriPermission(PrivilegedInstaller.PRIVILEGED_EXTENSION_PACKAGE_NAME,
apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.grantUriPermission("com.android.bluetooth", apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.grantUriPermission("com.mediatek.bluetooth", apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
return apkUri;
} else {
tempFile.setReadable(true, false);
return Uri.fromFile(tempFile);
}
}
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);
}
}
Uri getContentURI(Context context, String action) {
if (action.equals(BROADCAST_ACTION)) {
context.grantUriPermission(GOTO_PACKAGE_NAME, CONTENT_URI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
return CONTENT_URI;
} else if (action.equals(GOTO_BROADCAST_ACTION)) {
context.grantUriPermission(GOTO_PACKAGE_NAME, GOTO_CONTENT_URI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
return GOTO_CONTENT_URI;
} else {
return null;
}
}
/**
* Gets an intent to play a kml file in Google Earth.
*
* @param kmlFilePath the kml file path
*/
public static Intent getPlayInEarthIntent(Context context, String kmlFilePath) {
Uri uri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
.authority(MyTracksProviderUtils.AUTHORITY).path(kmlFilePath).build();
context.grantUriPermission(GOOGLE_EARTH_PACKAGE, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
return new Intent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_GRANT_READ_URI_PERMISSION)
.putExtra(GOOGLE_EARTH_TOUR_FEATURE_ID, TOUR_FEATURE_ID_VALUE)
.setClassName(GOOGLE_EARTH_PACKAGE, GOOGLE_EARTH_CLASS)
.setDataAndType(uri, SyncUtils.KMZ_MIME_TYPE);
}
/**
* Gets a valid File Uri to a file in the system
*
* @param file the {@code File} to open
* @param context Current context
* @return a File Uri to the given file
*/
public static Uri getFileUri(File file, Context context) {
String packageName = context.getApplicationContext().getPackageName() + ".provider";
Uri selectedUri = FileProvider.getUriForFile(context, packageName, file);
context.grantUriPermission(packageName, selectedUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
return selectedUri;
}
/**
* Gives the activities that can handle given intent permissions for given uri. Not doing so will result in a SecurityException from Android N upwards
*
* @param context context of the activity requesting resolution for given intent
* @param intent intent that needs to get resolved
* @param uri uri for which permissions are to be given
* @param flags what permissions are to be given
*/
public static void grantPermissionForUri(Context context, Intent intent, Uri uri, int flags) {
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, uri, flags);
}
}
/**
* Transfers the splash image to a Custom Tabs provider. The reading and decoding of the image
* happens synchronously, so it's recommended to call this method on a worker thread.
*
* This method should be called prior to launching the Activity.
* Pass additional parameters, such as background color, using
* {@link TrustedWebActivityIntentBuilder#setSplashScreenParams(Bundle)}.
*
* @param context {@link Context} to use.
* @param file {@link File} with the image.
* @param fileProviderAuthority authority of {@link FileProvider} used to generate an URI for
* the file.
* @param packageName Package name of Custom Tabs provider.
* @param session {@link CustomTabsSession} established with the Custom Tabs provider.
* @return True if the image was received and processed successfully.
*/
public static boolean transferSplashImage(Context context, File file,
String fileProviderAuthority, String packageName, CustomTabsSession session) {
Uri uri = FileProvider.getUriForFile(context, fileProviderAuthority, file);
context.grantUriPermission(packageName, uri, FLAG_GRANT_READ_URI_PERMISSION);
return session.receiveFile(uri, CustomTabsService.FILE_PURPOSE_TWA_SPLASH_IMAGE, null);
}