Search code examples
androidkotlindagger-hilt

How can i inject a class that needs context into Broadcast Receiver with hilt?


So i have a class that i would like to inject into BroadcastReceiver.

Here is the class:

class SomeClass @Inject contructor(@ActivityContext private val ctx: Context){
    fun doStuff(){...}
}

When i tried this i get this error: error: [Dagger/MissingBinding] @dagger.hilt.android.qualifiers.ActivityContext android.content.Context cannot be provided without an @Provides-annotated method.

@AndroidEntryPoint
class Broadcast: BroadcastReceiver() {
    @Inject lateinit var someClass: SomeClass

    override fun onReceive(context: Context?, intent: Intent?) {
          someClass.doStuff()
    }
}

I assume is a problem with the context of SomeClass because i tried it removing that parameter and it works.


Solution

  • Create this class:

    /**
     * This class is created in order to be able to @Inject variables into Broadcast Receiver.
     * Simply Inherit this class into whatever BroadcastReceiver you need and freely use Dagger-Hilt after.
     */
    
    abstract class HiltBroadcastReceiver : BroadcastReceiver() {
        @CallSuper
        override fun onReceive(context: Context, intent: Intent?) {
        }
    }
    

    Then, your BroadcastReceiver should look like this:

    @AndroidEntryPoint
    class BootReceiver : HiltBroadcastReceiver() {
    
        // Injection -> Example from my application
        @Inject
        lateinit var internetDaysLeftAlarm: InternetDaysLeftAlarm
    
        override fun onReceive(context: Context, intent: Intent?) {
            super.onReceive(context, intent)
            // Do whatever you need
        }
    }
    

    Also, as some people already mentioned here, watch out for @ActivityContext. Instead, you should just use @ApplicationContext