Android 分享图片和文案

一、业务描述

大多数App的需求中,有分享功能,点击唤起系统的分享栏,然后分享内容,例如指定文案,链接,图片等等。

二、实现逻辑

1.拿到要分享图片和内容

2.图片拿到缓存里,用于分享

3.使用FileProvider:用于创建一个 Content URI 并赋予临时的文件访问权限来代替 File URI 实现文件共享。

4.使用Intent实现分享,在intent里put Extra()图片和文本。

5.为intent添加Flag:shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

如果设置,此Intent的收件人将被授予对Intent数据中的URI及其ClipData中指定的任何URI执行读取操作的权限

三、实现代码:

根据控件临时生成一个图片进行分享,具体的逻辑请看实现代码,代码中有注释

        mBinding.shareRl.setOnClickListener {
            val width = mBinding.allContentCL.width
            val height = mBinding.allContentCL.height
            val bitmap: Bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            mBinding.allContentCL.draw(canvas)
            val imageFile = File(
                cacheDir, "image.png"
            )//从父抽象路径名和子路径名字符串创建新的文件实例。就是在系统的缓存目录里创建这个文件
            try {
                val fos = FileOutputStream(imageFile)//创建一个文件输出流,以写入由指定的file对象表示的文件。将创建一个新的FileDescriptor对象来表示此文件连接。
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)//将位图的压缩版本写入指定的输出流
                fos.close()
                val authority = "$packageName.fileprovider"
                val shareIntent = Intent()
                shareIntent.action = Intent.ACTION_SEND
                shareIntent.putExtra(Intent.EXTRA_TEXT, mBinding.cardDetailContent.text)
                shareIntent.putExtra(
                    Intent.EXTRA_STREAM, FileProvider.getUriForFile(this, authority, imageFile)
                )
                shareIntent.type = "image/*"
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                startActivity(
                    Intent.createChooser(
                        shareIntent, "Share Image"
                    )
                )
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }

tips:  代码val authority = "$packageName.fileprovider"

1.需要你在manifest文件中,注册你的FileProvider,

2.the.shy.world.top.one.myapplication替换为你的包路径。

 <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="the.shy.world.top.one.myapplication.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

3.file_paths.xml文件

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

 

如果想了解FileProvider和存储的特性,可以看下面的博客。

【精选】Android FileProvider特性与Intent重定向漏洞-CSDN博客

以及intent.createChooser()的使用

Intent.createChooser()-CSDN博客

猜你喜欢

转载自blog.csdn.net/LoveFHM/article/details/134242735