媒体应用通常包含按层次结构组织的媒体项集合。 例如,专辑中的歌曲或播放列表中的电视剧集。这种层次结构的 称为媒体库
<ph type="x-smartling-placeholder">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
对象包含有关客户端应用的内容树类型的额外信号
感兴趣的主题。