Search code examples
androidbroadcastreceiverkotlin

Kotlin: Call a function to update UI from BroadcastReceiver onReceive


I am new to Kotlin, and it seems awesome! Though today, I've been trying to do something that in Java was super simple, but I've got totally stuck.

I am using a broadcast receiver to determine when the device is connected/ disconnected from a power source. And all I need to do it update my UI accordingly.


My Code

Here's my BroadcastReceiver classs, and it seems to work fine.

class PlugInReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action

        if (action == Intent.ACTION_POWER_CONNECTED) {
            // Do stuff when power connected
        } 
        else if (action == Intent.ACTION_POWER_DISCONNECTED) {
            // Do more stuff when power disconnected
        }
    }
}

Now in my MainActivity (but somewhere else, later on), I want to update my UI when the intent is fired, for example in the function below, the background color changes.

private fun updateBackgroundColor( newBgColorId: Int = R.color.colorAccent){
    val mainLayout = findViewById<View>(R.id.mainLayout)
    val colorFade = ObjectAnimator.ofObject(
            mainLayout, "backgroundColor", ArgbEvaluator(), oldBgColor, newBgColor)
    colorFade.start()
}

The Question

How can I call a function on the MainActivity, or update my UI when the BroadcastReceiver fires an event?


What I've tried so far

  • I looked into having a static variable somewhere, storing the result of the BroadcastReciever, then an observable in my UI class, watching and calling appropriate function accordingly. Though after Googling how to do this, looks like that's not really a good approach in Kotlin.

  • Considered trying to run the BroadcastReciever on the UI thread, but that sounds like a terrible idea.

  • Tried mixing a Java implementation with my Kotlin class, but couldn't get it to work.

Frustratingly I found several very similar questions on SO. However their implementations seem to all use Java-specific features:


I'm sure this is a trivial question for most Android developers, but I am lost! Let me know if you need any more details. Thanks very much in advance!


Solution

  • Sharing the info to register BroadcastReceiver in Kotlin

    Step 1. Create BroadcastReceiver in MainActivity.kt

    private val mPlugInReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                Intent.ACTION_POWER_CONNECTED -> {
                    //update your main background color
                    updateBackgroundColor()
                }
                Intent.ACTION_POWER_DISCONNECTED -> {
                    //update your main background color
                    updateBackgroundColor()
                }
            }
        }
    }
    

    Step 2. Create IntentFilter

    private fun getIntentFilter(): IntentFilter {
        val iFilter = IntentFilter()
        iFilter.addAction(Intent.ACTION_POWER_CONNECTED)
        iFilter.addAction(Intent.ACTION_POWER_DISCONNECTED)
        return iFilter
    }
    

    Step 3. Register receiver at onStart()

    override fun onStart() {
        super.onStart()
        registerReceiver(mPlugInReceiver, getIntentFilter())
    }
    

    Step 4. Unregister receiver at onStop()

    override fun onStop() {
        super.onStop()
        unregisterReceiver(mPlugInReceiver)
    }
    

    If you have custom BroadcastReceiver, you can register using LocalBroadcastManager and create your local IntentFilter

    private val mLocalBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                AnyService.UPDATE_ANY -> {
    
                }
            }
        }
    }
    
    private fun getLocalIntentFilter(): IntentFilter {
        val iFilter = IntentFilter()
        iFilter.addAction(AnyService.UPDATE_ANY)
        return iFilter
    }
    

    Register local receiver LocalBroadcastManager.getInstance(applicationContext).registerReceiver(mLocalBroadcastReceiver, getLocalIntentFilter())

    Unregister local receiver LocalBroadcastManager.getInstance(applicationContext).unregisterReceiver(mLocalBroadcastReceiver)