You can’t call a method on a MainActivity instance when you are not sure there is one currently running.
Either you register/unregister the BroadcastReceiver in your onResume/onPause in which case you can safely pass a reference to the current instance of your MainActivity to your Receiver instance without risking Context leak (since Receiver would be tied to your MainActivity’s lifecycle). It would looks a bit like :
override fun onResume() {
//...
val r = Receiver(this)
...
this.registerReceiver(r, filter)
...
}
(see here → Context-registered receivers)
Or you have your receiver registered in AndroidManifest.xml, in which case you can :
- Fire and forget an Intent to the MainActivity that will be dropped if MainActivity is not running (in which case you need to create a receiver in your MainActivity somewhat like described here)
- Implement a registration system where your MainActivity would check in and out of the Receiver in its onResume/onPause : In this case you know in the receiver if there is a currently running instance of MainActivity and can decide what to do without leaking Context.