2016-01-21 62 views
2

我想讓我的用戶分享圖像。圖像生成時飛到byte[]。我不想將它寫入外部存儲器上的文件,因爲這需要額外的許可。分享圖像到Gmail應用失敗,破管

問題是,分享到Facebook,Twitter或Google Drive是否有效,但共享到Gmail卻不行。它失敗:

java.io.IOException: write failed: EPIPE (Broken pipe) 
     at libcore.io.IoBridge.write(IoBridge.java:502) 
     at java.io.FileOutputStream.write(FileOutputStream.java:186) 
     at java.io.OutputStream.write(OutputStream.java:82) 
     at sk.kios.scorabble.sharing.MediaContentProvider$TransferThread.run(MediaContentProvider.java:79) 
    Caused by: android.system.ErrnoException: write failed: EPIPE (Broken pipe) 
     at libcore.io.Posix.writeBytes(Native Method) 
     at libcore.io.Posix.write(Posix.java:223) 
     at libcore.io.BlockGuardOs.write(BlockGuardOs.java:313) 
     at libcore.io.IoBridge.write(IoBridge.java:497) 
     at java.io.FileOutputStream.write(FileOutputStream.java:186)  
     at java.io.OutputStream.write(OutputStream.java:82)  
     at sk.kios.scorabble.sharing.MediaContentProvider$TransferThread.run(MediaContentProvider.java:79)  

Gmail應用報告「無法附加空文件」。難道我做錯了什麼?這是我第一次這樣做。

這是我送的意圖:

Intent intent = new Intent(Intent.ACTION_SEND); 
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://" + MediaContentProvider.AUTHORITY + "/1")); 
intent.setType("image/png"); 
context.startActivity(intent); 

這是從我的ContentProvideropenFile方法:

@Override 
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { 
    byte data[] = myMethodToCreateImage(); 

    try { 
     ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe(); 
     new TransferThread(data, new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1])) 
      .start(); 

     return pipe[0]; 
    } catch (IOException e) { 
     throw new FileNotFoundException("Could not open pipe", e); 
    } 
} 

這是TransferThread類:

static class TransferThread extends Thread { 
    private final byte[] data; 
    private final OutputStream out; 

    TransferThread(byte[] data, OutputStream out) { 
     this.data = data; 
     this.out = out; 
    } 

    @Override 
    public void run() { 
     try { 
      out.write(data); 
     } catch (IOException e) { 
      Log.e(getClass().getSimpleName(), "Exception transferring file", e); 
     } 
     finally { 
      try { 
       out.close(); 
      } catch (IOException e) { 
       Log.e(TAG, "", e); 
      } 
     } 
    } 
} 

回答

1

我最初以爲這是一個gmail的bug,請看這裏:https://code.google.com/p/android-developer-preview/issues/detail?id=3141。但是這個bug只與android 6棉花糖有關,這不是我的情況。

原來,它工作得更好,如果你設置的URI不是Intent.EXTRA_STREAM,但intent.setDataAndType

Intent intent = new Intent(Intent.ACTION_SEND); 
intent.setDataAndType(Uri.parse("content://" + MediaContentProvider.AUTHORITY + "/1"), "image/png"); 
context.startActivity(intent);