关于媒体分享
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
无论是趣味图片、信息丰富的视频或引人入胜的音频片段,
让用户能够共享内容,丰富了他们的体验,并促进了
互动。本文档探讨了在 Android 设备上分享媒体内容的基础知识,
包括集成此功能所需的 API 和技术。
专为分享而设计
Android 的设计促进了应用之间的互操作性,这些应用使用基于
intent。intent 是对要执行的操作的抽象描述。借助 intent,应用可以相互通信,而无需知晓
相互了解具体细节。
当应用想要分享数据或发起操作时,它会创建一个 Intent,用于
指定内容的类型和操作。Android 系统会生成一个列表
可处理相应 Intent 的相关应用,让用户能够选择
应用。这种方法可打造一个协作式生态系统。
只需几行代码即可共享文本:
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, "This is my text to share.")
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, null)
startActivity(shareIntent)
createChooser
行显示了 Android Sharesheet 界面,
让用户能够与其他人分享信息(包括相关的应用推荐),
只需点按一下。您可以使用 Android Sharesheet 执行的其他操作包括:
如需详细了解 Android,请参阅向其他应用发送简单的数据
Sharesheet 及其使用方法。
提供直接共享目标,使
与您的应用分享网址、图片或其他类型的数据。直接
分享的工作原理是直接显示即时通讯应用和社交应用中的联系人
而无需用户先选择应用
搜索该联系人。
支持通过
OnReceiveContentListener
。借助此 API
用于处理从纯文本和样式文本到标记的所有内容的接收,
图片、视频、音频文件等内容可能来自图片
拖放或剪贴板。
Intent 只能包含少量数据,因此 Android 提供了一种
用于包含文件安全句柄的 intent。通过以下服务安全地分享媒体文件:
您的应用涉及:
如需详细了解如何安全地共享文件,请参阅关于共享文件。
文件。
无论您是在应用中与其他用户分享媒体内容,还是将媒体内容分享到
则您要确保分享的视频质量
分享体验
在质量和大小之间找到平衡
大型媒体文件可能会快速占用带宽和存储空间,
令人沮丧的延迟和潜在的数据超额费用。
压缩就是最好的方法。
fun hasHardwareEncodingSupportFor(mimeType: String): Boolean {
val codecList = MediaCodecList(REGULAR_CODECS)
val codecInfos = codecList.codecInfos
for ( codecInfo in codecInfos ) {
if (!codecInfo.isEncoder()) {
continue;
}
if (!codecInfo.isHardwareAccelerated()) {
continue;
}
val types: Array<String> = codecInfo.getSupportedTypes()
for (j in types.indices) {
if (types[j].equals(mimeType, ignoreCase = true)) {
return true
}
}
}
return false
}
// test for AV1 hardware encoding support
val hasAV1 = hasHardwareEncodingSupportFor("video/av01")
社交媒体平台通常会对分享的媒体内容强制执行特定的尺寸和宽高比。通过在分享前主动调整媒体文件的大小和剪裁,您可以避免用户在发布到喜爱的平台时出现意外失真或格式问题。
提供明确的说明和指导,告知用户如何在分享前优化媒体内容。这可能包括有关调整编码比特率、设置量化参数、选择视频格式、选择合适的文件大小或了解不同分享选项影响的提示。
为媒体添加相关元数据,例如标题、说明和标签
可以提高它们的可检测性。鼓励用户在分享时添加自己的说明和字幕,进一步打造个性化体验。
Jetpack ExifInterface 类将元数据写入 JPEG、PNG 和 WebP 中
Exif 标记的形式生成图片。
// sets the title of the image in the form of Exif data
val exif = ExifInterface(imageFile)
exif.setAttribute(ExifInterface.TAG_IMAGE_DESCRIPTION, "Beautiful sunset")
exif.saveAttributes()
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2024-09-12。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2024-09-12。"],[],[],null,["# About media sharing\n\nWhether it's a funny image, an informative video, or a captivating audio clip,\nenabling users to share content enriches their experience and promotes\nengagement. This document explores the essentials of sharing media on Android,\nincluding the APIs and techniques you need to integrate this capability.\n\nDesigned for sharing\n--------------------\n\nAndroid's design promotes interoperability between apps using a system based on\n*Intents*. An Intent is an abstract description of an operation to be performed.\nIntents allow apps to communicate with each other without having to know\nspecifics about each other.\n\nWhen an app wants to share data or initiate an action, it creates an Intent that\nspecifies the type of content and operation. The Android system presents a list\nof relevant apps that can handle that Intent, allowing the user to choose which\napp to use. This approach fosters a collaborative ecosystem.\n\nSharing text involves just a few lines of code: \n\n val sendIntent: Intent = Intent().apply {\n action = Intent.ACTION_SEND\n putExtra(Intent.EXTRA_TEXT, \"This is my text to share.\")\n type = \"text/plain\"\n }\n\n val shareIntent = Intent.createChooser(sendIntent, null)\n startActivity(shareIntent)\n\nThe [`createChooser`](/reference/android/content/Intent#createChooser(android.content.Intent,%20java.lang.CharSequence,%20android.content.IntentSender)) line displays the [Android Sharesheet](/training/sharing/send#why-to-use-system-sharesheet) UI, which\nlets users share information with people --- including relevant app suggestions ---\nwith a single tap. Other things you can do with the Android Sharesheet include:\n\n- [Find out when your users complete a share and to where](/training/sharing/send#share-interaction-data)\n- [Provide rich text content previews, starting in Android 10 (API level 29)](/training/sharing/send#adding-rich-content-previews)\n\nSee [Send simple data to other apps](/training/sharing/send) for more information about Android\nSharesheets and how to use them.\n\n[Provide Direct Share targets](/training/sharing/direct-share-targets) to make it easier and faster for users of\nother apps to share URLs, images, or other kinds of data with your app. [Direct\nShare](/codelabs/android-direct-share) works by presenting contacts from messaging and social apps directly\non the Android Sharesheet, without users having to select the app and then\nsearch for the contact.\n\nSupport [receiving rich content](/develop/ui/views/receive-rich-content) through an\n[`OnReceiveContentListener`](/reference/kotlin/androidx/core/view/OnReceiveContentListener). This API provides a single place for your\ncode to handle receiving all content, from plain and styled text to markup,\nimages, videos, audio files, and others. The content can come from image\nkeyboards, drag and drop, or the clipboard.\n\nShare media files\n-----------------\n\nIntents can only contain a small amount of data, so Android provides a way for\nIntents to contain a secure handle to files. Sharing media files securely from\nyour app involves:\n\n- [Configure your app to offer a secure handle to the file](/training/secure-file-sharing/setup-sharing) --- in the form of a content URI --- using the Android `FileProvider` component.\n- [Specify sharable directories](/training/secure-file-sharing/setup-sharing#DefineMetaData) in your manifest.\n- Use [`getUriForFile`](/reference/androidx/core/content/FileProvider#getUriForFile(android.content.Context,%20java.lang.String,%20java.io.File)) to create a content URL that functions as a secure handle to the file.\n- Create an Intent that [grants permissions](/training/secure-file-sharing/share-file#GrantPermissions) to the file.\n\nSee [About sharing files](/training/secure-file-sharing) for more information about how to securely share\nfiles.\n\nOptimize media for sharing\n--------------------------\n\nWhether you're sharing media to other users in your app, or sharing media to\nanother app, you want to make sure you share media that offers a high quality\nsharing experience.\n\n### Striking the balance between quality and size\n\nLarge media files can quickly consume bandwidth and storage, leading to\nfrustrating delays and potential data overage charges for your users.\nCompression is your best friend here.\n\n- **Image compression** : [Utilize modern image compression formats](/develop/ui/views/graphics/reduce-image-sizes) like WebP and AVIF, which offer superior compression ratios compared to traditional JPEGs without significant quality loss. Experiment with different quality settings to find the sweet spot.\n- **Video compression** : [Leverage the power of AV1 or H.265 (HEVC)](/media/platform/transcoding) video compression to provide better compression efficiency while maintaining excellent visual quality. You can check for the presence of hardware encoding on Android 10+ devices, as well as the [`mediaPerformanceClass`](/topic/performance/performance-class) to help determine what your device can best support. Consider offering different resolution options to cater to varying user preferences and network conditions.\n\n fun hasHardwareEncodingSupportFor(mimeType: String): Boolean {\n val codecList = MediaCodecList(REGULAR_CODECS)\n val codecInfos = codecList.codecInfos\n for ( codecInfo in codecInfos ) {\n if (!codecInfo.isEncoder()) {\n continue;\n }\n if (!codecInfo.isHardwareAccelerated()) {\n continue;\n }\n val types: Array\u003cString\u003e = codecInfo.getSupportedTypes()\n for (j in types.indices) {\n if (types[j].equals(mimeType, ignoreCase = true)) {\n return true\n }\n }\n }\n return false\n }\n // test for AV1 hardware encoding support\n val hasAV1 = hasHardwareEncodingSupportFor(\"video/av01\")\n\n### Adapting media\n\nSocial media platforms often enforce specific dimensions and aspect ratios for\nshared media. By [proactively resizing and cropping media files before\nsharing](/media/optimize/sharing#resolution_cropping_and_scaling), you can avoid unexpected distortion or formatting issues when\nusers post to their favorite platforms.\n\nProvide clear instructions and guidance on how users can optimize their media\nbefore sharing. This could include tips on adjusting [encoding bitrates](/media/optimize/sharing#bitrate),\nsetting [quantization parameters](/media/optimize/sharing#quantization_parameter_qp), [choosing the video format](/media/media3/transformer/transformations#transcode),\nselecting appropriate file sizes, or understanding the impact of different\nsharing options.\n\n### Enhancing media discoverability\n\nAdding relevant metadata, such as titles, descriptions, and tags to your media\nfiles can improve their discoverability. Encourage users to add their own\ndescriptions and captions when sharing, further personalizing the experience.\n\n#### Add metadata to images\n\nThe [Jetpack ExifInterface](/reference/androidx/exifinterface/media/ExifInterface) class writes metadata into JPEG, PNG, and WebP\nimages in the form of Exif tags. \n\n // sets the title of the image in the form of Exif data\n val exif = ExifInterface(imageFile)\n exif.setAttribute(ExifInterface.TAG_IMAGE_DESCRIPTION, \"Beautiful sunset\")\n exif.saveAttributes()"]]