Android Image Sharing Intent分享Drawable图片报错File format not supported求解
错误根因
- 核心逻辑错误:你调用
Uri.parse(user.toString())生成Uri的方式完全不合法,User数据类默认toString()输出的是类名+属性的格式化字符串,并非可识别的图片资源路径,系统无法解析该内容对应图片,因此抛出文件格式不支持错误。 - 权限问题:你存储的
imagepic是应用内drawable资源的int id,第三方应用没有权限直接读取你应用内部的资源文件,必须转成公开可访问的Uri才能分享。
解决方案
步骤1:配置FileProvider(Android 7.0及以上强制要求)
在AndroidManifest.xml的<application>标签内添加Provider配置:
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
在res/xml目录下新建file_paths.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <cache-path name="shared_images" path="images/" /> </paths>
步骤2:新增Drawable转共享Uri的工具方法
fun getShareUriFromDrawable(context: Context, drawableId: Int): Uri? { // 将Drawable转成Bitmap val drawable = ContextCompat.getDrawable(context, drawableId) ?: return null val bitmap = when (drawable) { is BitmapDrawable -> drawable.bitmap else -> Bitmap.createBitmap( drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888 ).also { bitmap -> val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) } } // 把Bitmap存入应用缓存目录 val imageCacheDir = File(context.cacheDir, "images").apply { if (!exists()) mkdirs() } val shareImageFile = File(imageCacheDir, "share_${System.currentTimeMillis()}.png") return try { FileOutputStream(shareImageFile).use { outputStream -> bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) } // 通过FileProvider生成外部可访问的Uri FileProvider.getUriForFile( context, "${context.packageName}.fileprovider", shareImageFile ) } catch (e: IOException) { e.printStackTrace() null } }
如果项目仍使用Android Support库,将androidx.core.content.FileProvider替换为android.support.v4.content.FileProvider即可。
步骤3:修改分享逻辑
fun sharepic(user: User) { val shareUri = getShareUriFromDrawable(itemView.context, user.imagepic) ?: return Log.i(TAG, shareUri.toString()) val shareIntent = Intent(Intent.ACTION_SEND).apply { type = "image/*" addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) putExtra(Intent.EXTRA_STREAM, shareUri) } startActivity( itemView.context, Intent.createChooser(shareIntent, "Share Image"), null ) }
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

