我有一个位于以下位置的图像(它位于我的android工作区资源中),
D:\Android\WorkSpace\myprojectname\res\drawable-hdpi
我已使用以下代码行将此图片附加到电子邮件中,但它似乎无法正常工作,它会发送电子邮件但不会有附件。
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM,Uri.parse("android.resource://com.mywebsite.myprojectname/" + R.drawable.image));
这是错的吗?
答案 0 :(得分:1)
Resources res = this.getResources();
Bitmap bm = BitmapFactory.decodeResource(res, R.drawable.image);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory(), "image.jpg");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
FileOutputStream fo = null;
try {
fo = new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Uri uri = Uri.fromFile(f);
之后,
如果您要发送电子邮件,请执行以下操作,
intent.putExtra(Intent.EXTRA_STREAM, uri);
它肯定会起作用。它完全有效。试试吧。
答案 1 :(得分:0)
嗯,第一个问题是,即使URI格式正确(我怀疑),该文件也将位于应用程序的沙箱中,电子邮件活动(或任何其他活动)无法访问该沙箱。物)。在任何情况下,您都必须将该文件写入SD卡并让电子邮件程序从那里读取。您可以使用以下代码输出位图:
Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.image);
File file = new File(Environment.getExternalStorageDirectory(), "forEmail.PNG");
OutputStream outStream = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
然后使用Uri.fromFile()
从上面定义的文件中生成URI:
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.fromFile(file));
(来自here改编的资源代码)
答案 2 :(得分:0)
其他答案也可能有效(虽然它们对我不起作用)!我只使用下面的一行代码运行它,这非常简单容易。感谢大家。
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.image));
我认为我的问题是我将包名错误,但使用getPackageName()方法解决了问题!