图片分享功能

  1. 声明 FileProvider
    在 AndroidManifest.xml 的 application 下面增加 provider
1
2
3
4
5
6
7
8
9
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="app包名.fileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
  1. 创建一个 XML 文件用于定义共享文件的路径。
    在 res/xml 目录下创建一个 file_paths.xml 文件:
1
2
3
4
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_files" path="." />
</paths>
  1. 使用 FileProvider 来获取共享文件的 URI,添加临时的读取权限
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    fun share(filePath:String){
    val file = File(filePath)
    if (!file.exists()) return

    //获取需要分享的图片在App中的uri
    val uri = FileProvider.getUriForFile(
    requireContext(),
    authority: "com.example.littlepainter.fileprovider",
    file)

    //添加临时的读取权限
    val intent = Intent(lntent.ACTION_SEND)
    //向Intent中添加要分享的数据
    intent.putExtra(lntent.EXTRA_STREAM,uri)

    //类型
    intent.type = "image/jpeg"


    //Intent.createChooser()方法创建一个选择器,让用户选择分享的目标应用程序。
    //第一个参数是我们要发送的Intent对象,第二个参数是在选择器中显示的标题,这里为"图片分享"。
    startActivity(lntent.createChooser(intent, title:"图片分享"))
    }
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2023-2025 Annie
  • Visitors: | Views:

嘿嘿 请我吃小蛋糕吧~

支付宝
微信