Search code examples
androiddependency-injectionbroadcastreceiverdagger

How to inject into a BroadcastReceiver


Does someone already had to inject an already existing class, with some business logic, into a BroadcastReceiver using dagger?

I'm using dagger 1 and already found a nice example (https://github.com/adennie/fb-android-dagger) but, I could not find how we can add an already existing class, which belongs to a different module, into a BroadcastReceiver.

Any help or advice would be greatly appreciated.


Solution

  • I managed to inject use cases into my Broadcast by defining a Module which provide the use cases I need and I add the Module on the onReceive method, check the code below:

    My BroadcastReceiverModule:

    @Module(injects = { MyBroadcastReceiver.class }, addsTo = MyAppModule.class)
    public class BroadcastReceiverModule {
        @Provides @Singleton MyUtilsClass providesMyUtilsClass(MyUtilsClassImpl myUtilsClass) {
            return myUtilsClass;
        }
        @Provides @Singleton MyUseCase providesMyUseCase(MyUseCaseImpl myUseCaseUtils) {
            return myUseCaseUtils;
        }
    }
    

    My BroadCastReceiver:

    @Inject MyUtilsClass myUtilsClass;
    @Inject MyUseCase myUseCase;
    @Override public void onReceive(Context context, Intent intent) {
        AcidApplication.getScopedGraph(getModules().toArray()).inject(this);
        myUseCase.call();
        myUtilsClass.doSomething();
    }
    protected List<Object> getModules() {
        List<Object> result = new ArrayList<>();
        result.add(new BroadcastReceiverModule());
        return result;
    }