媒體應用程式通常包含按階層分類的媒體項目集合。例如播放清單中的歌曲或電視劇集。這個媒體項目階層稱為媒體庫。
MediaLibraryService
提供標準化 API,用於提供及存取媒體程式庫。舉例來說,在媒體應用程式新增 Android Auto 支援功能時,這項功能就能派上用場,為媒體庫提供專屬的驅動程式安全 UI。
建構 MediaLibraryService
實作 MediaLibraryService
與實作 MediaSessionService
類似,但在 onGetSession()
方法中,應傳回 MediaLibrarySession
,而不是 MediaSession
。
Kotlin
class PlaybackService : MediaLibraryService() { var mediaLibrarySession: MediaLibrarySession? = null var callback: MediaLibrarySession.Callback = object : MediaLibrarySession.Callback {...} // If desired, validate the controller before returning the media library session override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession? = mediaLibrarySession // Create your player and media library session in the onCreate lifecycle event override fun onCreate() { super.onCreate() val player = ExoPlayer.Builder(this).build() mediaLibrarySession = MediaLibrarySession.Builder(this, player, callback).build() } // Remember to release the player and media library session in onDestroy override fun onDestroy() { mediaLibrarySession?.run { player.release() release() mediaLibrarySession = null } super.onDestroy() } }
Java
class PlaybackService extends MediaLibraryService { MediaLibrarySession mediaLibrarySession = null; MediaLibrarySession.Callback callback = new MediaLibrarySession.Callback() {...}; @Override public MediaLibrarySession onGetSession(MediaSession.ControllerInfo controllerInfo) { // If desired, validate the controller before returning the media library session return mediaLibrarySession; } // Create your player and media library session in the onCreate lifecycle event @Override public void onCreate() { super.onCreate(); ExoPlayer player = new ExoPlayer.Builder(this).build(); mediaLibrarySession = new MediaLibrarySession.Builder(this, player, callback).build(); } // Remember to release the player and media library session in onDestroy @Override public void onDestroy() { if (mediaLibrarySession != null) { mediaLibrarySession.getPlayer().release(); mediaLibrarySession.release(); mediaLibrarySession = null; } super.onDestroy(); } }
請記得在資訊清單檔案中宣告 Service
和必要權限:
<service
android:name=".PlaybackService"
android:foregroundServiceType="mediaPlayback"
android:exported="true">
<intent-filter>
<action android:name="androidx.media3.session.MediaSessionService"/>
</intent-filter>
</service>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- For targetSdk 34+ -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
使用 MediaLibrarySession
MediaLibraryService
API 會預期您的媒體庫採用樹狀格式結構,其中包含一個根節點以及子節點 (可能可播放或進一步可瀏覽)。
MediaLibrarySession
會擴充 MediaSession
API,以便新增內容瀏覽 API。相較於 MediaSession
回呼,MediaLibrarySession
回呼會新增下列方法:
onGetLibraryRoot()
:適用於用戶端要求內容樹狀結構的根MediaItem
onGetChildren()
用於當用戶端要求內容樹狀結構中MediaItem
的子項onGetSearchResult()
用於指定查詢內容樹狀結構中的搜尋結果
相關的回呼方法會包含 LibraryParams
物件,並針對用戶端應用程式感興趣的內容樹狀結構類型提供額外信號。