Using Dagger 2 to inject into service

前端 未结 2 1283
挽巷
挽巷 2020-12-24 01:57

I have an app which is basically a service that runs all the time and alarms the user when something happens.

When the service creates the alarm, it needs to give it

2条回答
  •  情歌与酒
    2020-12-24 02:11

    I know this question already has an answer but there are an other way to do this

    first make your application extend HasServiceInjector like this:

    public class App extends Application implements HasActivityInjector, 
    HasServiceInjector {
    
    @Inject
    DispatchingAndroidInjector dispatchingActivityInjector;
    @Inject
    DispatchingAndroidInjector dispatchingServiceInjector;
    
    @Override
    public void onCreate() {
        super.onCreate();
        AppInjector.init(this);
    }
    
    @Override
    public AndroidInjector activityInjector() {
        return dispatchingActivityInjector;
    }
    
    @Override
    public AndroidInjector serviceInjector() {
        return dispatchingServiceInjector;
    }
    
    }
    

    then create a ServiceBuilderModule this will perform injection over services:

    @Module
    abstract class ServiceBuilderModule {
    
    @ContributesAndroidInjector
    abstract MyService contributeMyService();
    
    }
    

    then register the new module to your component

    @Component(modules = {
        AndroidSupportInjectionModule.class,
        AppModule.class,
        ActivityBuilderModule.class,
        ServiceBuilderModule.class
     })
     @Singleton
     public interface AppComponent {
    
     @Component.Builder
     interface Builder {
        @BindsInstance
        Builder application(App application);
    
        AppComponent build();
     }
    
     void inject(App app);
    
     }
    

    then override the onCreate method of your service and add AndroidInjection.inject(this) like below code :

    public class MyService extends Service {
    
    @Override
    public void onCreate() {
        AndroidInjection.inject(this);
        super.onCreate();
    }
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    }
    

    code in kotlin is exact conversion of the code above. hope this helps some coders from now on.

提交回复
热议问题