You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Intent分享多张图片Uri到WhatsApp出现文件格式不支持错误问询

多图分享到WhatsApp失败修复方案

错误点说明

  • 多图分享不能使用Intent.ACTION_SEND,必须使用适配多内容的Intent.ACTION_SEND_MULTIPLE动作
  • 图片压缩格式与文件后缀不匹配:代码中用PNG格式压缩,但文件后缀命名为.jpg,导致WhatsApp识别文件格式异常
  • 构造的Uri列表没有传入Intent,也没有在主线程触发分享动作
  • 输出流使用后未主动关闭,存在资源泄漏风险

修正后代码

val cachePath = File(requireContext().cacheDir, "images")
cachePath.mkdirs()
val uriList = arrayListOf<Uri>()
// 多图分享替换为ACTION_SEND_MULTIPLE
val intent = Intent(Intent.ACTION_SEND_MULTIPLE)
intent.type = "image/*"
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

// 建议替换GlobalScope为lifecycleScope避免内存泄漏
lifecycleScope.launch(Dispatchers.IO) {
    shareClicked.images.forEach {
        val loader = ImageLoader(requireContext())
        val request = ImageRequest.Builder(requireContext())
            .data(it.image)
            .allowHardware(false)
            .build()

        val result = (loader.execute(request) as SuccessResult).drawable
        val bitmap = (result as BitmapDrawable).bitmap

        val uuid = UUID.randomUUID()
        val targetFile = File(cachePath, "${uuid}.jpg")
        val stream = FileOutputStream(targetFile)
        // 压缩格式和后缀统一为JPG,质量可按需调整
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream)
        // 主动关闭流释放资源
        stream.flush()
        stream.close()

        val contentUri: Uri = FileProvider.getUriForFile(
            requireContext(),
            // 此处替换为你应用实际的FileProvider authorities
            "${requireContext().packageName}.fileprovider",
            targetFile
        )
        uriList.add(contentUri)
    }

    // 切回主线程启动分享
    withContext(Dispatchers.Main) {
        // 传入Uri列表
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList)
        startActivity(Intent.createChooser(intent, "分享图片到"))
    }
}

额外校验项

确认AndroidManifest.xml中配置的FileProvider的xml/file_paths配置包含缓存目录路径,示例配置如下:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="images" path="images/" />
</paths>

确认传入FileProvider.getUriForFile的第二个参数和Manifest中注册的android:authorities完全一致

内容的提问来源于stack exchange,提问作者Kashif Mehmood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:27:02