繁体   English   中英

如何格式化要在uri.parse()中使用的路径

[英]how to format the path to use in uri.parse() for android

我的图片位于以下位置(位于我的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));

这个错吗?

    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);

它肯定会工作。 它完全起作用了。 试试吧。

好吧,第一个问题是,即使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));

(从此处改编的资源文件代码)

其他答案也可能有用(尽管它们对我不起作用)! 我只用下面的一行代码就可以运行它,这非常简单。 感谢大家。

emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.image));

我认为我的问题是我把软件包名称放错了,但是使用getPackageName()方法可以解决问题!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM