我想从应用程序的范围存储中共享图像,这就是我遇到此异常的地方。搜索了几个小时,最后,我找到了这个博客。
它有点长,所以我在这里分享要点,但我会建议你仔细阅读。
底线是您不能从应用程序的范围存储中共享任何内容。同样在 Android 12 中,intent 选择器底部对话框会显示您正在共享的图像的预览,顺便说一句,这非常酷,但它无法从作用域存储 URI 加载预览。
解决方案是在缓存目录中创建您“打算”共享的文件的副本。
val cachePath = File(externalCacheDir, "my_images/")
cachePath.mkdirs()
val bitmap = loadImageFromStorage(currentQuote.bookId)
val file = File(cachePath, "cache.png")
val fileOutputStream: FileOutputStream
try {
fileOutputStream = FileOutputStream(file)
bitmap?.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
fileOutputStream.flush()
fileOutputStream.close()
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
val cacheImageUri: Uri = FileProvider.getUriForFile(this, applicationContext.packageName + ".provider", file)
val intent = Intent(Intent.ACTION_SEND).apply {
clipData = ClipData.newRawUri(null, cacheImageUri)
putExtra(Intent.EXTRA_STREAM, cacheImageUri)
type = "image/ *"
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(Intent.createChooser(intent, null))
这就是我从范围存储加载文件的方式
fun Context.loadImageFromStorage(path: String): Bitmap? {
try {
val file = getFile(path)
val bitmap = BitmapFactory.decodeStream(FileInputStream(file))
return bitmap
} catch (e: Exception) {
e.printStackTrace()
//Returning file from public storage in case the file is stored in public storage
return BitmapFactory.decodeStream(FileInputStream(File(path)))
}
return null
}
fun Context.getFile(path: String): File? {
val cw = ContextWrapper(this)
val directory = cw.getDir("image_dir", Context.MODE_PRIVATE)
if (!directory.exists())
directory.mkdir()
try {
val fileName = directory.absolutePath + "/" + path.split("/").last()
return File(fileName)
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
最后,不要忘记更新您的provider_paths.xml
文件
<external-cache-path name="external_cache" path="." />
<external-cache-path name="external_files" path="my_images/"/>