媒体应用通常包含以层次结构组织的媒体内容集合。例如,专辑中的歌曲或播放列表中的电视剧集。这种媒体内容的层次结构称为媒体库。
MediaLibraryService
提供标准化 API 来提供和访问媒体库。例如,在向媒体应用(为媒体库提供自己的驾驶员安全界面)添加对 Android Auto 的支持时,此功能会很有用。
构建 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
对象,该对象包含有关客户端应用感兴趣的内容树类型的其他信号。