有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 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_CAPTUREACTION_VIEW,但同样的技术也适用于ACTION_SEND