5

我正在尝试从我的应用程序中发送带有徽标的电子邮件。
但是当附件为字符串格式(应该是 png)时,我会收到电子邮件。
我的代码:

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("application/image");

    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.fb_share_description));
    intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://my.package/" + R.drawable.ic_launcher));
   Intent chooser = Intent.createChooser(intent, "share");
   startActivity(chooser);

我应该怎么办?

4

1 回答 1

8

您不能从内部资源将文件附加到电子邮件。您必须先将其复制到存储的常用区域,例如 SD 卡。

InputStream in = null;
OutputStream out = null;
try {
    in = getResources().openRawResource(R.drawable.ic_launcher);
    out = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "image.png"));
    copyFile(in, out);
    in.close();
    in = null;
    out.flush();
    out.close();
    out = null;
} catch (Exception e) {
    Log.e("tag", e.getMessage());
    e.printStackTrace();
}


private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
}

//Send the file
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/html");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "File attached");
Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.png"));
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Send mail..."));

这是必需的,因为您与应用程序捆绑的资源是只读的并且被沙箱化到您的应用程序中。电子邮件客户端收到的 URI 是它无法访问的。

于 2013-08-19T10:32:32.787 回答