将图像发送到另一个应用程序

时间:2017-12-24 00:09:45

标签: java android android-intent

我正在尝试实施“分享”按钮。有必要发一张照片。

这就是我正在做的事情:

Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();

File outputDir = context.getCacheDir();
File outputFile = null;
try {
    outputFile = File.createTempFile("temp_", ".jpg", outputDir);
} catch (IOException e) {
    e.printStackTrace();
}

FileOutputStream fileOutputStream = null;
try {
    fileOutputStream = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);

try {
    fileOutputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, 
getResources().getText(R.string.send_via)));

但是我收到一条消息,说上传图片是不可能的。怎么了?

1 个答案:

答案 0 :(得分:0)

首先,第三方应用无权访问internal storage部分中的文件。

其次,在Android 7.0及更高版本中,您无法使用file Uri值,例如Uri.fromFile()返回的值。

要解决这两个问题,请使用FileProvider将图片提供给其他应用。使用FileProvider.getUriForFile()代替Uri.fromFile(),并务必将FLAG_GRANT_READ_URI_PERMISSION添加到Intent

This sample app演示了如何将FileProvider与第三方应用一起使用(适用于ACTION_IMAGE_CAPTUREACTION_VIEW,但相同的技术适用于ACTION_SEND)。