Android RecyclerView中使用Intent分享图片报转型错误问题求助
问题排查与解决方案
核心错误原因
- 直接将
User对象传入File构造方法,File类不支持接收自定义User类型作为入参,这是抛出转型错误的直接原因 - 存在
drawable下的图片是应用内置资源,不是本地存储的实体文件,无法直接通过Uri.fromFile获取路径 - 即使修复上述问题,Android 7.0及以上版本使用
Uri.fromFile分享文件还会抛出FileUriExposedException异常,需要适配FileProvider
可行解决方案
步骤1:新增drawable转缓存文件Uri的工具方法
在RecyclerView Adapter中新增如下方法:
fun getDrawableUri(context: Context, drawableId: Int): Uri { // 将drawable资源转为Bitmap val drawable = ContextCompat.getDrawable(context, drawableId)!! val bitmap = (drawable as BitmapDrawable).bitmap // 在应用缓存目录创建存储分享图片的文件夹 val shareCacheDir = File(context.cacheDir, "shared_images") shareCacheDir.mkdirs() // 生成图片缓存文件 val imageFile = File(shareCacheDir, "share_${System.currentTimeMillis()}.png") // 将Bitmap写入缓存文件 val fos = FileOutputStream(imageFile) bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos) fos.flush() fos.close() // 通过FileProvider生成可对外分享的Uri return FileProvider.getUriForFile( context, "${context.packageName}.fileprovider", imageFile ) }
步骤2:配置FileProvider
在AndroidManifest.xml的application标签内添加如下配置:
<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>
步骤3:新建FileProvider路径配置文件
在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="shared_images/" /> </paths>
步骤4:修改分享函数
fun shareImage(user: User) { val imageUri = getDrawableUri(itemView.context, user.imagepic) val intent = Intent(Intent.ACTION_SEND) intent.type = "image/*" intent.putExtra(Intent.EXTRA_STREAM, imageUri) // 给接收应用授予Uri临时读取权限 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) itemView.context.startActivity(Intent.createChooser(intent,"Share to :")) }
注意事项
- 如果需要分享JPG格式图片,将Bitmap压缩方法中的
Bitmap.CompressFormat.PNG改为Bitmap.CompressFormat.JPEG即可 - 确保项目已引入androidx core依赖,多数Android项目默认已集成
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

