It may be too late to answer this question, but I AppWidgetProvider an AppWidgetProvider example from my recent project in which I tried to implement an AppWidgetProvider which is a direct subclass of BroadcastReceiver .
We need to implement a modified service in BroadcastReceiver :
@Module public class NetModule { @Singleton @Provides public WidgetService provideWidgetService(Application application, OkHttpClient client, Gson gson) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(application.getString(R.string.api_url)) .client(client) .build() .create(WidgetService.class); } }
Create another abstract @Module for the with abstract methods annotated with @ContributesAndroidInjector that return the BroadcastReceiver you want @ContributesAndroidInjector :
@Module public abstract class WidgetsModule { @ContributesAndroidInjector abstract IngredientsWidget contributesIngredientsWidget(); }
If you forgot to add this module, you will receive an error message:
java.lang.IllegalArgumentException: injector factory not bound to class <>
Then a component with both modules except AndroidInjectionModule
@Singleton @Component(modules = {AndroidInjectionModule.class, NetModule.class, WidgetsModule.class}) public interface AppComponent { void inject(RecipesApp recipesApp); }
Then, in your Application class, you implement the HasBroadcastReceiverInjector interface.
public class RecipesApp extends Application implements HasBroadcastReceiverInjector { @Inject DispatchingAndroidInjector<BroadcastReceiver> broadcastReceiverInjector; @Override public void onCreate() { super.onCreate(); component().inject(this); } public AppComponent component() { return DaggerAppComponent.builder() .build(); } @Override public AndroidInjector<BroadcastReceiver> broadcastReceiverInjector() { return broadcastReceiverInjector; } }
Finally, you can add your BroadcastReceiver inside onReceive () before calling super ().
public class IngredientsWidget extends AppWidgetProvider { @Inject public WidgetService api; @Override public void onReceive(Context context, Intent intent) { AndroidInjection.inject(this, context); super.onReceive(context, intent); } }
You can learn more about how to embed documents on Android components.
I built a small sample: broadcast injection .