分享纯文本

1
2
3
4
5
6
7
8
9
10
11
fun shareText(text: String) {
val sendIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, text)
type = "text/plain"
}

// 创建一个选择器,让用户选择用哪个 App 分享
val shareIntent = Intent.createChooser(sendIntent, "分享文本到...")
startActivity(shareIntent)
}

注意:始终使用 Intent.createChooser() 是一个好习惯。这会强制系统每次都显示一个应用选择列表,避免用户因为设置了某个应用的“默认操作”而无法选择其他应用。

分享单张图片或单个文件

  • AndroidManifest.xml 中声明 FileProvider
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<manifest ...>
<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>
...
</application>
</manifest>
  • 创建 res/xml/file_paths.xml 文件
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="my_cache_images" path="images/"/>
<files-path name="my_files" path="docs/"/>
<external-path name="my_external_files" path="."/>
</paths>
  • 编写分享代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private fun saveImgAndGetUri(context: Context,bitmap: Bitmap):Uri{
val imageFolder= File(context.cacheDir,"images")
val uri:Uri?
imageFolder.mkdirs()
val file= File(imageFolder,"shared_image.png")
val stream= FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.PNG,90,stream)
stream.flush()
stream.close()
uri = FileProvider.getUriForFile(
context,
"com.example.daysmatter.fileprovider", // 必须和 Manifest 中的 authorities 一致
file
)
return uri
}
private fun shareImage(context: Context, uri: Uri) {
// 创建 Intent
val shareIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_STREAM, uri)
type = "image/png" // 设置正确的 MIME Type
// 授予临时读取权限
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
// 4. 启动选择器
startActivity(Intent.createChooser(shareIntent, "分享图片到..."))
}

分享多张图片或多个文件

与分享单张基本相同,有个别点有差异

  • Intent Action: Intent.ACTION_SEND_MULTIPLE

  • 分享内容: 使用 putParcelableArrayListExtra(Intent.EXTRA_STREAM, ...) 存放一个包含多个 UriArrayList

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fun shareMultipleImages(context: Context, imageFiles: List<File>) {
val uriList = ArrayList<Uri>()
imageFiles.forEach { file ->
val uri = FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
file
)
uriList.add(uri)
}

val shareIntent = Intent().apply {
action = Intent.ACTION_SEND_MULTIPLE
putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList)
type = "image/*" // 可以使用通配符
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}

startActivity(Intent.createChooser(shareIntent, "分享多张图片..."))
}