java将图像发送到另一个应用程序
我正在尝试实现“共享”按钮。有必要发一张照片
我就是这么做的:
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 楼答案
首先,第三方应用程序无权访问internal storage部分中的文件
其次,在Android 7.0+上,不能使用}值,例如
file
{Uri.fromFile()
返回的值要解决这两个问题,请使用
FileProvider
将图像提供给其他应用程序。使用FileProvider.getUriForFile()
而不是Uri.fromFile()
,并确保将FLAG_GRANT_READ_URI_PERMISSION
添加到Intent
This sample app演示了在第三方应用程序中使用
FileProvider
(对于ACTION_IMAGE_CAPTURE
和ACTION_VIEW
,但同样的技术也适用于ACTION_SEND
)