簡體   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