我在我的应用程序的活动和片段中创建了多个 MediaBrowserCompat 实例,在这种情况下,每个组件都必须创建 MediaBrowserCompat 并将其连接到服务等等。为了更简单,使用 Dagger 只创建一个 MediaBrowserCompat 实例并将其注入到我想要的任何地方是不是一个坏主意?
像这样:
这是我创建 MediaBrowserCompat 的 MediaBrowserModule
@Module
class MediaBrowserModule {
@Provides
@Singleton
fun providesMediaBrowserCompat(
context: Context,
componentName: ComponentName,
connectionCallback: MediaBrowserConnectionCallback
): MediaBrowserCompat = MediaBrowserCompat(context, componentName, connectionCallback, null)
@Provides
fun providesMediaBrowserServiceComponentName(context: Context): ComponentName =
ComponentName(context, MediaBrowserService::class.java)
@Provides
@Singleton
fun providesMediaBrowserConnectionStatus(): MutableLiveData<MediaBrowserConnectionCallback.ConnectionStatus> =
MutableLiveData()
}
MediaBrowser 连接回调实现:
class MediaBrowserConnectionCallback @Inject constructor(private val connectionStatus: MutableLiveData<ConnectionStatus>) :
MediaBrowserCompat.ConnectionCallback() {
override fun onConnected() {
super.onConnected()
connectionStatus.postValue(ConnectionStatus.Connected)
}
override fun onConnectionSuspended() {
super.onConnectionSuspended()
connectionStatus.postValue(ConnectionStatus.Suspended)
}
override fun onConnectionFailed() {
super.onConnectionFailed()
connectionStatus.postValue(ConnectionStatus.Failed)
}
enum class ConnectionStatus {
Connected, Suspended, Failed
}
}
最后,我可以在任何地方使用它,如下所示:
class MainActivity : DaggerAppCompatActivity(), Observer<MediaBrowserConnectionCallback.ConnectionStatus> {
@Inject
lateinit var connectionState: MutableLiveData<MediaBrowserConnectionCallback.ConnectionStatus>
@Inject
lateinit var mediaBrowserCompat: MediaBrowserCompat
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
connectionState.observe(this, this)
}
override fun onStart() {
super.onStart()
if (!mediaBrowserCompat.isConnected)
mediaBrowserCompat.connect()
}
override fun onChanged(status: MediaBrowserConnectionCallback.ConnectionStatus?) {
Toast.makeText(this, status?.name, Toast.LENGTH_LONG).show()
}
}
谢谢。