Android equivalent to NSNotificationCenter

前端 未结 8 2060
旧时难觅i
旧时难觅i 2020-12-22 15:35

In the process of porting an iPhone application over to android, I am looking for the best way to communicate within the app. Intents seem to be the way to go, is this the b

相关标签:
8条回答
  • 2020-12-22 16:26

    I wrote a wrapper that can do this same job, equivalent to iOS using LiveData

    Wrapper:

    class ObserverNotify {
        private val liveData = MutableLiveData<Nothing>()
    
    
        fun postNotification() {
            GlobalScope.launch {
                withContext(Dispatchers.Main) {
                    liveData.value = liveData.value
                }
            }
        }
    
        fun observeForever(observer: () -> Unit) {
            liveData.observeForever { observer() }
        }
    
        fun observe(owner: LifecycleOwner, observer: () -> Unit) {
            liveData.observe(owner) { observer()}
        }
    
    }
    
    class ObserverNotifyWithData<T> {
        private val liveData = MutableLiveData<T>()
    
    
        fun postNotification(data: T) {
            GlobalScope.launch {
                withContext(Dispatchers.Main) {
                    liveData.value = data
                }
            }
        }
    
        fun observeForever(observer: (T) -> Unit) {
            liveData.observeForever { observer(it) }
        }
    
        fun observe(owner: LifecycleOwner, observer: (T) -> Unit) {
            liveData.observe(owner) { observer(it) }
        }
    
    }
    

    Declaring observer types:

    object ObserverCenter {
        val moveMusicToBeTheNextOne: ObserverNotifyWithData<Music> by lazy { ObserverNotifyWithData() }
        val playNextMusic: ObserverNotify by lazy { ObserverNotify() }
        val newFCMTokenDidHandle: ObserverNotifyWithData<String?> by lazy { ObserverNotifyWithData() }
    }
    

    In the activity to observe:

    ObserverCenter.newFCMTokenDidHandle.observe(this) {
        // Do stuff
    }
    

    To notify:

    ObserverCenter.playNextMusic.postNotification()
    ObserverCenter.newFCMTokenDidHandle.postNotification("MyData")
    
    0 讨论(0)
  • 2020-12-22 16:33

    You could use this: http://developer.android.com/reference/android/content/BroadcastReceiver.html, which gives a similar behavior.

    You can register receivers programmatically through Context.registerReceiver(BroadcastReceiver, IntentFilter) and it will capture intents sent through Context.sendBroadcast(Intent).

    Note, though, that a receiver will not get notifications if its activity (context) has been paused.

    0 讨论(0)
提交回复
热议问题