You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android端如何分享从REST API流式获取的指定视频片段

Got it, let's walk through how to build this share feature for your on-demand streaming video clips—since you're loading clips only when users tap thumbnails and using streaming playback, we need to focus on sharing the right assets and leveraging system-level share capabilities. Here's a step-by-step breakdown:

Core Concept First

The key here is that you can't share a locally stored file (since you're streaming on-demand), so you'll need to rely on publicly accessible streaming URLs for each clip. Make sure your API returns a direct, playable stream URL (like HLS .m3u8, DASH .mpd, or a standard MP4 URL) alongside other metadata when a user selects a thumbnail.

1. Store Selected Clip Metadata

When a user taps a thumbnail and you fetch the clip via API, save the critical details (stream URL, title, description) in an accessible place (like a ViewModel, page state variable, or global store). This lets you quickly access the data when the user initiates a share.

Example (Android Kotlin)

// Data class to hold clip details
data class VideoClip(
    val id: String,
    val streamUrl: String,
    val title: String,
    val description: String,
    val thumbnailUrl: String
)

// Track the currently selected clip
private var selectedClip: VideoClip? = null

fun onThumbnailClicked(clipId: String) {
    apiService.getVideoClip(clipId).enqueue(object : Callback<VideoClip> {
        override fun onResponse(call: Call<VideoClip>, response: Response<VideoClip>) {
            response.body()?.let { clip ->
                selectedClip = clip
                // Load stream into your video player
                videoPlayer.setDataSource(clip.streamUrl)
                videoPlayer.prepare()
                videoPlayer.start()
            }
        }

        override fun onFailure(call: Call<VideoClip>, t: Throwable) {
            // Handle API error
        }
    })
}

2. Implement System-Level Sharing

Use your platform's built-in share functionality to launch the system share panel. This ensures you support all installed apps that handle video sharing (like WhatsApp, Telegram, email, etc.).

Android Implementation

Use Intent.ACTION_SEND to package the clip's details and launch the share chooser:

fun shareSelectedClip() {
    selectedClip?.let { clip ->
        val shareIntent = Intent(Intent.ACTION_SEND).apply {
            type = "video/*" // Use specific type like "application/x-mpegURL" for HLS if needed
            putExtra(Intent.EXTRA_TITLE, clip.title)
            putExtra(Intent.EXTRA_TEXT, "${clip.description}\n\nWatch the clip: ${clip.streamUrl}")
            putExtra(Intent.EXTRA_STREAM, Uri.parse(clip.streamUrl))
        }

        // Show share chooser
        startActivity(Intent.createChooser(shareIntent, "Share video clip via"))
    } ?: run {
        // Prompt user to select a clip first
        Toast.makeText(context, "Please select a video clip to share", Toast.LENGTH_SHORT).show()
    }
}

iOS Implementation (Swift)

Use UIActivityViewController to present the share options:

// Assume you have a stored selectedClip variable
private var selectedClip: VideoClip?

func shareSelectedClip() {
    guard let clip = selectedClip, let streamURL = URL(string: clip.streamUrl) else {
        // Alert user to select a clip
        let alert = UIAlertController(title: "Heads Up", message: "Please select a video clip first", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
        return
    }

    let activityItems: [Any] = [clip.title, clip.description, streamURL]
    let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)

    // Handle iPad popover positioning
    if let popoverController = activityVC.popoverPresentationController {
        popoverController.sourceView = shareButton
        popoverController.sourceRect = shareButton.bounds
    }

    present(activityVC, animated: true)
}

3. Handle Streaming Compatibility & Security

  • Publicly Accessible URLs: Ensure your stream URLs don't require user authentication (unless you generate short-lived, signed URLs with a token). If your clips are behind a login, create time-limited signed URLs via your server so shared links work for recipients.
  • Format Support: Some apps may not support HLS/DASH streams. If possible, provide a fallback MP4 URL in your API response, or note in the share text that the link works with streaming-enabled apps.
  • Test Across Apps: Validate sharing to popular apps (WhatsApp, Gmail, Telegram) to ensure links are recognized and playable.

4. Polish User Experience

  • Disable Share When No Clip Selected: Gray out or disable the share button until a user selects a clip.
  • Loading State for Signed URLs: If you need to generate a signed URL at share time, show a loading spinner to avoid confusion.
  • Filter Relevant Apps (Android only): You can filter out apps that can't handle video sharing to streamline the chooser:
    val resolvedActivities = packageManager.queryIntentActivities(shareIntent, 0)
    if (resolvedActivities.isEmpty()) {
        Toast.makeText(context, "No apps available to share video", Toast.LENGTH_SHORT).show()
        return
    }
    // Create a filtered chooser with only relevant apps
    val chooserIntent = Intent.createChooser(shareIntent, "Share via")
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, resolvedActivities.map {
        Intent(shareIntent).apply {
            setClassName(it.activityInfo.packageName, it.activityInfo.name)
        }
    }.toTypedArray())
    startActivity(chooserIntent)
    

内容的提问来源于stack exchange,提问作者Adithya.K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:14:48