我正在开发 Android Auto Media App,但无法理解 MediaBrowserService 的生命周期

I am developing Android Auto Media App and not able to understand life cycle of MediaBrowserService

在创建 android 自动媒体应用程序 MusicService class 时创建扩展 MediaBrowserService,这两个方法自动实现 onGetRoot 和 onLoadChildren。 任何人都可以详细解释每件事是如何工作的。

摘自MusicPlayer.java

This class provides a MediaBrowser through a service. It exposes the media library to a browsing client, through the onGetRoot and onLoadChildren methods

onGetRoot(..): Returns root id 如果客户端包有访问媒体信息的权限(Returns null 如果客户端是不允许)。 Source

onLoadChildren:Returns 媒体项的子项列表。 Source

要了解两者的实现,请检查 MusicPlayer.java

中的实现

MediaBrowserService 的生命周期看起来像它扩展的简单 Service 的生命周期。 From documentation:

The lifecycle of the MediaBrowserService is controlled by the way it is created, the number of clients that have are to it, and the calls it receives from media session callbacks. To summarize:

  • The service is created when it is started in response to a media button or when an activity binds to it (after connecting via its MediaBrowser).
  • The media session onPlay() callback should include code that calls startService(). This ensures that the service starts and continues to run, even when all UI MediaBrowser activities that are bound to it unbind.
  • The onStop() callback should call stopSelf(). If the service was started, this stops it. In addition, the service is destroyed if there are no activities bound to it. Otherwise, the service remains bound until all its activities unbind. (If a subsequent startService() call is received before the service is destroyed, the pending stop is cancelled.)

The following flowchart demonstrates how the lifecycle of a service is managed. The variable counter tracks the number of bound clients:

onGetRootonLoadChildren 用于 manage client connections

但是要使用 MediaBrowserService 这还不够,所以您应该阅读 this documentation(跟随嵌套链接)。