Android:如何使用 grantUriPermission 创建和发送带有位图附件的电子邮件
在我的应用程序中,我正在尝试创建一个包含位图对象中包含的图像的电子邮件。
private void sendEmailWithBitmapAttached(){
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Email Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Email Body");
emailIntent.setType("image/png");
ContentResolver cr = getContentResolver();
// insert the image and create a path
String imageBitmapPath = MediaStore.Images.Media.insertImage(cr, bitmapForEmail,"title", "description");
// create a uri
Uri imageUri = Uri.parse(imageBitmapPath);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
// send the email
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
这在Android 2.3中工作正常。
但是使用更高版本,它会产生以下错误:
07-13 23:01:01.252: E/MediaStore(5194): Failed to insert image
07-13 23:01:01.252: E/MediaStore(5194): java.lang.SecurityException:
Permission Denial:
writing com.android.providers.media.MediaProvider
uri content://media/external/images/media from
pid=5194, uid=10151 requires
android.permission.WRITE_EXTERNAL_STORAGE,
or grantUriPermission()
因此,根据错误消息的建议,我试图授予UriPermission。
grantUriPermission(String toPackage, Uri uri, int modeFlags)
但我不确定该放什么给Package或uri
但是,再次使用错误消息,我修改了代码,如下所示:
private void sendEmailWithBitmapAttached(){
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Email Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Email Body");
emailIntent.setType("image/png");
ContentResolver cr = getContentResolver();
// create a Uri for the content provider suggested by the error message
Uri uri = Uri.parse("content://media/external/images/media");
// create a package provider string suggested by the error messge.
String provider = "com.android.providers.media.MediaProvider";
// grant all three uri permissions!
grantUriPermission(provider, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
grantUriPermission(provider, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
grantUriPermission(provider, uri, Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
// insert the image and create a path
String imageBitmapPath = MediaStore.Images.Media.insertImage(cr, bitmapForEmail,"title", "description");
// create a uri
Uri imageUri = Uri.parse(imageBitmapPath);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
// send the email
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
我得到了完全相同的错误。
一个善良的灵魂能否给我一个提示,说明如何照顾grantUriPermission的uri和提供者物品?这是正确的方法吗?
非常感谢您的任何帮助,提示,指南或建议,你可以提供!