2016-05-13 48 views
0

我試圖使用意圖共享圖像。這裏是我創建的方法僅限圖片與WhatsApp共享,但未與Android中的其他應用程序共享

public void shareImg(int fileNum) //Consider fileNum=R.drawable.img 
{ 

    Uri uri= Uri.parse("android.resource://" 
      + context.getPackageName() + "/" + fileNum); 
    Intent share=new Intent(); 
    share.setAction(Intent.ACTION_SEND); 
    share.setType("image/*"); 
    share.putExtra(Intent.EXTRA_STREAM, uri); 
    share.putExtra(Intent.EXTRA_TEXT, "Sent Via ---"); 

    Intent chooser= Intent.createChooser(share, "Share Via"); 
    context.startActivity(chooser); 

} 

該圖像與WhatsApp與標題正確共享。但是當我嘗試與Gmail,Messenger等應用共享時,它會在Toast中顯示錯誤。

例如,

Gmail提示:無法附加空文件

使者說:無法轉換爲圖像

+1

幾個應用程序支持''android.resource'方案Uri'。 – CommonsWare

+0

爲了實現這一點,您需要先將該資源繪製到存儲中,然後與文件URI共享。 –

+0

但是,當我從畫廊或其他應用程序中選擇 – ss007

回答

0

可以使用份額意圖共享圖像,但你到的圖像進行解碼,以本地化的位圖

Intent intent = new Intent(Intent.ACTION_SEND); 
intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image"); 
String path = Images.Media.insertImage(getContentResolver(), loadedImage, "", null); 
Uri screenshotUri = Uri.parse(path); 

intent.putExtra(Intent.EXTRA_STREAM, screenshotUri); 
intent.setType("image/*"); 
startActivity(Intent.createChooser(intent, "Share image via...")); 

loadedImage是圖像

+0

對不起,但沒有工作 – ss007

0

的路徑下面是可以執行的步驟。

步驟1。首先,創建從抽拉

Drawable d = ImagesArrayList.get(0); 
Bitmap bitmap = ((BitmapDrawable)d).getBitmap(); 

步驟2位圖。位圖保存到文件

FileOutputStream out = null; 
String filename = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg"; 
try { 
    out = new FileOutputStream(filename); 
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance 
    // PNG is a lossless format, the compression factor (100) is ignored 
} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     if (out != null) { 
      out.close(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

步驟3。分享這個圖片用fileurl文件。與共享圖庫圖像共享圖像。

完整的答案

Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.xxxx); // your resource ID here 
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/LatestShare.jpg"; 
OutputStream out = null; 
File file=new File(path); 
try { 
    out = new FileOutputStream(file); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); 
    out.flush(); 
    out.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
path=file.getPath(); 
Uri bmpUri = Uri.parse("file://"+path); 
Intent shareIntent = new Intent(); 
shareIntent = new Intent(android.content.Intent.ACTION_SEND); 
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri); 
shareIntent.setType("image/jpg"); 
startActivity(Intent.createChooser(shareIntent,"Share with")); 
+0

對不起,但已經嘗試過,沒有工作! – ss007

+0

保存時是否有任何錯誤。描述你用這個解決方案面臨的問題 –

+0

它給NullPointerException – ss007