關於媒體分享
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
無論是有趣的圖片、資訊影片或吸引人的音訊片段
讓使用者分享內容、提升體驗,
提高參與度本文件將探討在 Android 上分享媒體的基本要件。
包括整合此功能所需的 API 和技術。
便於分享
Android 的設計可讓使用者運用根據
意圖。「意圖」是待執行作業的摘要說明。
意圖可讓應用程式在不需知情的情況下彼此通訊
好奇心
當應用程式想要分享資料或啟動動作時,會建立意圖,指定內容和作業類型。Android 系統會顯示一份清單
能夠處理該意圖的相關應用程式,讓使用者自行選擇
要使用的應用程式這個做法可促進協同合作的生態系統。
分享文字只需幾行程式碼:
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 UI,
允許使用者與他人分享資訊 (包括相關的應用程式建議),
就能使用這項功能Android Sharesheet 還提供:
如要進一步瞭解 Android,請參閱「傳送簡單資料給其他應用程式」。
共用試算表及使用方式
提供直接分享目標,讓
也能將網址、圖片或其他種類的資料提供給您的應用程式。直接
分享:直接透過訊息和社交應用程式分享聯絡人畫面
使用者不必選取應用程式
搜尋所需聯絡人。
支援透過
OnReceiveContentListener
。這個 API 可讓您在同一個位置
處理所有內容,包括純文字、樣式化文字、標記等
圖片、影片、音訊檔案等內容可以來自圖片
鍵盤、拖曳操作或剪貼簿。
意圖只能包含少量資料,因此 Android 提供
意圖包含檔案的安全控制代碼。透過以下裝置安全分享媒體檔案:
包括:
如要進一步瞭解如何安全地共用檔案,請參閱「關於共用檔案」一文
檔案。
你是否要與應用程式中的其他使用者分享媒體,或將媒體內容分享給
也別忘了分享 優質媒體內容
分享經驗
在品質與尺寸之間取得平衡
大型媒體檔案可能會快速消耗頻寬和儲存空間,
使用者可能會因此遭遇延遲情況,也較有可能產生超額的資料超額費用。
壓縮是你最好的朋友,
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 類別會以 EXIF 標記的形式,將中繼資料寫入 JPEG、PNG 和 WebP 圖片。
// 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 和/或其關係企業的商標或註冊商標。
上次更新時間: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"]],["上次更新時間: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()"]]