使用Intent.ACTION_SEND附加图片

时间:2019-06-10 08:31:28

标签: android image android-intent

我正在尝试通过以下代码使用不同的应用程序附加图像:

val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.putExtra(Intent.EXTRA_TEXT, "Test example")
sendIntent.type = "image/png"
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(logo.absolutePath))
startActivity(sendIntent)

附加的图像是使用以下代码生成的:

// Generate file for application logo
val path = Environment.getExternalStorageDirectory().absolutePath
val logo = File(path, "logo.png")

// If logo doesn't exist
if (!logo.exists())
{
    // Create new file
    logo.createNewFile()

    // Save application logo to new file
    val fOut = FileOutputStream(logo)
    val image = BitmapFactory.decodeResource(applicationContext.resources, R.mipmap.ic_launcher_round)
    image.compress(Bitmap.CompressFormat.PNG, 100, fOut)
    fOut.flush()
    fOut.close()
}

但是当我试图以此目的打开GMAIL时,只有文本显示错误为Couldn't attach file的应用。

我想念什么?

  

编辑

这是另一种解决方案:android.os.FileUriExposedException: file.jpg exposed beyond app through ClipData.Item.getUri()

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

2 个答案:

答案 0 :(得分:1)

在Android N上,您必须使用FileProvider来获取Uri

请参见下面的文件共享示例。

ArrayList<Uri> files = new ArrayList<Uri>();

        File file = new File(<Your File Path>);
        Uri uri;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(DetailActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        files.add(uri);

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND_MULTIPLE);
        intent.putExtra(Intent.EXTRA_SUBJECT, "Product Sharing");
        intent.setType("image/jpeg");
        intent.putExtra(Intent.EXTRA_TEXT, "ANY TEXT MESSAGE");
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
        startActivity(intent);

在ApplicationMan标签中的AndroidManifest.xml中放置以下代码

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>

将filepath.xml文件放置在xml资源目录中

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

答案 1 :(得分:0)

没有文件提供者,您将无法发送文件。例如,Gmail不请求READ/WRITE_EXTERNAL_STORAGE权限,因此它无法访问您的文件。您必须将文件提供程序与GRANT_READ_URI_PERMISSION一起使用。您可以在这里阅读更多内容

  1. https://developer.android.com/reference/android/support/v4/content/FileProvider
  2. https://developer.android.com/training/secure-file-sharing/setup-sharing
  3. https://developer.android.com/training/secure-file-sharing/share-file