Android equivalent to NSNotificationCenter

前端 未结 8 2077
旧时难觅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:13

    Kotlin: Here's a @Shiki's version in Kotlin with a little bit refactor in a fragment.

    1. Register the observer in Fragment.

    Fragment.kt

    class MyFragment : Fragment() {
    
        private var mContext: Context? = null
    
        private val mMessageReceiver = object: BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                //Do something here after you get the notification
                myViewModel.reloadData()
            }
        }
    
        override fun onAttach(context: Context) {
            super.onAttach(context)
    
            mContext = context
        }
    
        override fun onStart() {
            super.onStart()
            registerSomeUpdate()
        }
    
        override fun onDestroy() {
            LocalBroadcastManager.getInstance(mContext!!).unregisterReceiver(mMessageReceiver)
            super.onDestroy()
        }
    
        private fun registerSomeUpdate() {
            LocalBroadcastManager.getInstance(mContext!!).registerReceiver(mMessageReceiver, IntentFilter(Constant.NOTIFICATION_SOMETHING_HAPPEN))
        }
    
    }
    
    1. Post notification anywhere. Only you need the context.

      LocalBroadcastManager.getInstance(context).sendBroadcast(Intent(Constant.NOTIFICATION_SOMETHING_HAPPEN))```
      

    PS:

    1. you can add a Constant.kt like me for well organize the notifications. Constant.kt
    object Constant {
        const val NOTIFICATION_SOMETHING_HAPPEN = "notification_something_happened_locally"
    }
    
    1. For the context in a fragment, you can use activity (sometimes null) or conext like what I used.

提交回复
热议问题