How to use LocalBroadcastManager?

后端 未结 13 3281
天命终不由人
天命终不由人 2020-11-21 04:15

How to use/locate LocalBroadcastManager as described in google docs and Service broadcast doc?

I tried to google it, but there is no code available to s

13条回答
  •  春和景丽
    2020-11-21 04:53

    I am an iOS dev, so I made a solution similar to NotificationCenter:

    object NotificationCenter {
        var observers: MutableMap> = mutableMapOf()
    
        fun addObserver(observer: NotificationObserver, notificationName: NotificationName) {
            var os = observers[notificationName.value]
            if (os == null) {
                os = mutableListOf()
                observers[notificationName.value] = os
            }
            os.add(observer)
        }
    
        fun removeObserver(observer: NotificationObserver, notificationName: NotificationName) {
            val os = observers[notificationName.value]
            if (os != null) {
                os.remove(observer)
            }
        }
    
        fun removeObserver(observer:NotificationObserver) {
            observers.forEach { name, mutableList ->
                if (mutableList.contains(observer)) {
                    mutableList.remove(observer)
                }
            }
        }
    
        fun postNotification(notificationName: NotificationName, obj: Any?) {
            val os = observers[notificationName.value]
            if (os != null) {
                os.forEach {observer ->
                    observer.onNotification(notificationName,obj)
                }
            }
        }
    }
    
    interface NotificationObserver {
        fun onNotification(name: NotificationName,obj:Any?)
    }
    
    enum class NotificationName(val value: String) {
        onPlayerStatReceived("on player stat received"),
        ...
    }
    

    Some class that want to observe notification must conform to observer protocol:

    class MainActivity : AppCompatActivity(), NotificationObserver {
        override fun onCreate(savedInstanceState: Bundle?) {
            ...
            NotificationCenter.addObserver(this,NotificationName.onPlayerStatReceived)
        }
        override fun onDestroy() {
            ...
            super.onDestroy()
            NotificationCenter.removeObserver(this)
        }
    
        ...
        override fun onNotification(name: NotificationName, obj: Any?) {
            when (name) {
                NotificationName.onPlayerStatReceived -> {
                    Log.d(tag, "onPlayerStatReceived")
                }
                else -> Log.e(tag, "Notification not handled")
            }
        }
    

    Finally, post some notification to observers:

    NotificationCenter.postNotification(NotificationName.onPlayerStatReceived,null)
    

提交回复
热议问题