管理電視使用者互動情形

在電視直播體驗中,使用者變更頻道後,系統會短暫顯示頻道和節目資訊,隨後資訊就會消失。其他類型的資訊 (例如訊息「請勿在家嘗試」、字幕或廣告) 可能需要保留。與任何電視應用程式一樣,這類資訊不應干擾螢幕上播放的節目內容。

圖 1. 電視直播應用程式中的疊加訊息。

此外,請根據內容分級和家長監護設定,考量是否應顯示特定節目內容,以及應用程式在內容遭到封鎖或無法使用時的行為和通知方式。本課程將說明如何根據這些考量因素,開發電視輸入裝置的使用者體驗。

試用 TV Input Service 範例應用程式。

將播放器與介面整合

電視輸入內容必須將影片算繪至 Surface 物件,該物件是由 TvInputService.Session.onSetSurface() 方法傳遞。以下範例說明如何使用 MediaPlayer 例項,在 Surface 物件中播放內容:

Kotlin

override fun onSetSurface(surface: Surface?): Boolean {
    player?.setSurface(surface)
    mSurface = surface
    return true
}

override fun onSetStreamVolume(volume: Float) {
    player?.setVolume(volume, volume)
    mVolume = volume
}

Java

@Override
public boolean onSetSurface(Surface surface) {
    if (player != null) {
        player.setSurface(surface);
    }
    mSurface = surface;
    return true;
}

@Override
public void onSetStreamVolume(float volume) {
    if (player != null) {
        player.setVolume(volume, volume);
    }
    mVolume = volume;
}

同樣地,以下說明如何使用 ExoPlayer 執行這項操作:

Kotlin

override fun onSetSurface(surface: Surface?): Boolean {
    player?.createMessage(videoRenderer)?.apply {
        type = MSG_SET_SURFACE
        payload = surface
        send()
    }
    mSurface = surface
    return true
}

override fun onSetStreamVolume(volume: Float) {
    player?.createMessage(audioRenderer)?.apply {
        type = MSG_SET_VOLUME
        payload = volume
        send()
    }
    mVolume = volume
}

Java

@Override
public boolean onSetSurface(@Nullable Surface surface) {
    if (player != null) {
        player.createMessage(videoRenderer)
                .setType(MSG_SET_SURFACE)
                .setPayload(surface)
                .send();
    }
    mSurface = surface;
    return true;
}

@Override
public void onSetStreamVolume(float volume) {
    if (player != null) {
        player.createMessage(videoRenderer)
                .setType(MSG_SET_VOLUME)
                .setPayload(volume)
                .send();
    }
    mVolume = volume;
}

使用疊加畫面

使用疊加畫面顯示字幕、訊息、廣告或 MHEG-5 資料廣播。根據預設,疊加畫面會停用。您可以在建立工作階段時呼叫 TvInputService.Session.setOverlayViewEnabled(true) 啟用這項功能,如下列範例所示:

Kotlin

override fun onCreateSession(inputId: String): Session =
        onCreateSessionInternal(inputId).apply {
            setOverlayViewEnabled(true)
            sessions.add(this)
        }

Java

@Override
public final Session onCreateSession(String inputId) {
    BaseTvInputSessionImpl session = onCreateSessionInternal(inputId);
    session.setOverlayViewEnabled(true);
    sessions.add(session);
    return session;
}

使用 TvInputService.Session.onCreateOverlayView() 傳回的疊加層 View 物件,如下所示:

Kotlin

override fun onCreateOverlayView(): View =
        (context.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater).run {
            inflate(R.layout.overlayview, null).apply {
                subtitleView = findViewById<SubtitleView>(R.id.subtitles).apply {
                    // Configure the subtitle view.
                    val captionStyle: CaptionStyleCompat =
                            CaptionStyleCompat.createFromCaptionStyle(captioningManager.userStyle)
                    setStyle(captionStyle)
                    setFractionalTextSize(captioningManager.fontScale)
                }
            }
        }

Java

@Override
public View onCreateOverlayView() {
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.overlayview, null);
    subtitleView = (SubtitleView) view.findViewById(R.id.subtitles);

    // Configure the subtitle view.
    CaptionStyleCompat captionStyle;
    captionStyle = CaptionStyleCompat.createFromCaptionStyle(
            captioningManager.getUserStyle());
    subtitleView.setStyle(captionStyle);
    subtitleView.setFractionalTextSize(captioningManager.fontScale);
    return view;
}

疊加層的佈局定義可能如下所示:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.exoplayer.text.SubtitleView
        android:id="@+id/subtitles"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="32dp"
        android:visibility="invisible"/>
</FrameLayout>

控制內容

當使用者選擇頻道時,您的電視輸入會處理 TvInputService.Session 物件中的 onTune() 回呼。系統電視應用程式的家長監護功能會根據內容分級來決定顯示哪些內容。 以下各節說明如何使用與系統電視應用程式通訊的 TvInputService.Session notify 方法管理頻道和節目選擇。

使視頻不可用

當使用者切換頻道時,您需要確保在電視輸入渲染內容之前,螢幕上不會顯示任何雜訊的視訊瑕疵。當呼叫 TvInputService.Session.onTune() 時,可以透過呼叫 TvInputService.Session.notifyVideoUnavailable() 並傳遞 VIDEO_UNAVAILABLE_REASON_TUNING 常數來阻止影片的播放,如下例所示。

Kotlin

override fun onTune(channelUri: Uri): Boolean {
    subtitleView?.visibility = View.INVISIBLE
    notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING)
    unblockedRatingSet.clear()

    dbHandler.apply {
        removeCallbacks(playCurrentProgramRunnable)
        playCurrentProgramRunnable = PlayCurrentProgramRunnable(channelUri)
        post(playCurrentProgramRunnable)
    }
    return true
}

Java

@Override
public boolean onTune(Uri channelUri) {
    if (subtitleView != null) {
        subtitleView.setVisibility(View.INVISIBLE);
    }
    notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING);
    unblockedRatingSet.clear();

    dbHandler.removeCallbacks(playCurrentProgramRunnable);
    playCurrentProgramRunnable = new PlayCurrentProgramRunnable(channelUri);
    dbHandler.post(playCurrentProgramRunnable);
    return true;
}

然後,當內容渲染到 Surface 時,呼叫 TvInputService.Session.notifyVideoAvailable() 來允許影片顯示,如下所示:

Kotlin

fun onRenderedFirstFrame(surface:Surface) {
    firstFrameDrawn = true
    notifyVideoAvailable()
}

Java

@Override
public void onRenderedFirstFrame(Surface surface) {
    firstFrameDrawn = true;
    notifyVideoAvailable();
}

這種過渡只持續不到一秒鐘,但顯示空白螢幕在視覺上比讓畫面閃爍奇怪的斑點和抖動要好。

另請參閱 將播放器與 surface,以瞭解有關使用 Surface 渲染影片的更多資訊。

提供家長監護

要確定給定內容是否被家長控制和內容分級阻止,您需要檢查 TvInputManager 類別方法、isParentalControlsEnabled()isRatingBlocked(android.media.tv.TvContentRating)。您可能還需要確保內容的 TvContentRating 包含在目前允許的內容評級集中。以下範例展示了這些考慮因素。

Kotlin

private fun checkContentBlockNeeded() {
    currentContentRating?.also { rating ->
        if (!tvInputManager.isParentalControlsEnabled
                || !tvInputManager.isRatingBlocked(rating)
                || unblockedRatingSet.contains(rating)) {
            // Content rating is changed so we don't need to block anymore.
            // Unblock content here explicitly to resume playback.
            unblockContent(null)
            return
        }
    }
    lastBlockedRating = currentContentRating
    player?.run {
        // Children restricted content might be blocked by TV app as well,
        // but TIF should do its best not to show any single frame of blocked content.
        releasePlayer()
    }

    notifyContentBlocked(currentContentRating)
}

Java

private void checkContentBlockNeeded() {
    if (currentContentRating == null || !tvInputManager.isParentalControlsEnabled()
            || !tvInputManager.isRatingBlocked(currentContentRating)
            || unblockedRatingSet.contains(currentContentRating)) {
        // Content rating is changed so we don't need to block anymore.
        // Unblock content here explicitly to resume playback.
        unblockContent(null);
        return;
    }

    lastBlockedRating = currentContentRating;
    if (player != null) {
        // Children restricted content might be blocked by TV app as well,
        // but TIF should do its best not to show any single frame of blocked content.
        releasePlayer();
    }

    notifyContentBlocked(currentContentRating);
}

在確定是否應該阻止內容後,透過呼叫 TvInputService.Session 方法 notifyContentAllowed()notifyContentBlocked() 通知系統電視應用程序,如前面的範例所示。

使用 TvContentRating 類別和 TvContentRating.createRating() 方法產生系統定義的 COLUMN_CONTENT_RATING 字串,如下所示:

Kotlin

val rating = TvContentRating.createRating(
        "com.android.tv",
        "US_TV",
        "US_TV_PG",
        "US_TV_D", "US_TV_L"
)

Java

TvContentRating rating = TvContentRating.createRating(
    "com.android.tv",
    "US_TV",
    "US_TV_PG",
    "US_TV_D", "US_TV_L");

處理曲目選擇

TvTrackInfo 類別包含有關媒體軌道的信息,例如軌道類型(視訊、音訊或字幕)等等。

首次電視輸入會話能夠獲取曲目資訊時,應呼叫 TvInputService.Session.notifyTracksChanged() 並傳入所有曲目清單以更新系統電視應用程式。當曲目資訊發生變化時,再次呼叫 notifyTracksChanged() 以更新系統。

如果給定軌道類型有多個軌道可用,例如不同語言的字幕,則系統電視應用程式會為使用者提供一個介面來選擇特定軌道。您的電視輸入透過調用 notifyTrackSelected() 來回應系統電視應用程式的 onSelectTrack() 調用,如下例所示。請注意,當 null 作為曲目 ID 傳遞時,此 會取消選擇 曲目。

Kotlin

override fun onSelectTrack(type: Int, trackId: String?): Boolean =
        mPlayer?.let { player ->
            if (type == TvTrackInfo.TYPE_SUBTITLE) {
                if (!captionEnabled && trackId != null) return false
                selectedSubtitleTrackId = trackId
                subtitleView.visibility = if (trackId == null) View.INVISIBLE else View.VISIBLE
            }
            player.trackInfo.indexOfFirst { it.trackType == type }.let { trackIndex ->
                if( trackIndex >= 0) {
                    player.selectTrack(trackIndex)
                    notifyTrackSelected(type, trackId)
                    true
                } else false
            }
        } ?: false

Java

@Override
public boolean onSelectTrack(int type, String trackId) {
    if (player != null) {
        if (type == TvTrackInfo.TYPE_SUBTITLE) {
            if (!captionEnabled && trackId != null) {
                return false;
            }
            selectedSubtitleTrackId = trackId;
            if (trackId == null) {
                subtitleView.setVisibility(View.INVISIBLE);
            }
        }
        int trackIndex = -1;
        MediaPlayer.TrackInfo[] trackInfos = player.getTrackInfo();
        for (int index = 0; index < trackInfos.length; index++) {
            MediaPlayer.TrackInfo trackInfo = trackInfos[index];
            if (trackInfo.getTrackType() == type) {
                trackIndex = index;
                break;
            }
        }
        if (trackIndex >= 0) {
            player.selectTrack(trackIndex);
            notifyTrackSelected(type, trackId);
            return true;
        }
    }
    return false;
}