10

Is it possible to Inject object exposed through dagger into android.app.IntentService? If so, how I can do that?

I want to have something like that.

public class SomeService extends android.app.IntentService {

@Inject
Synchronizer synchronizer;

public SomeService(String name) {
    super(name);
}

@Override
protected void onHandleIntent(Intent intent) {
    synchronizer.doSynch();
}

}

lstrzelecki
  • 671
  • 7
  • 13

1 Answers1

25

From a dagger point of view, IntentService isn't different from any other class.

However Dagger 2.x provides a new way, how you can inject dependencies into Android's base building element (like Service, Activities, Fragment etc.). Here sample calls for both versions.

Dagger 1.x

Injection can look like that (I'm assuming, that your Application has an instance of ObjectGraph and exposes method inject). Of course, don't forget add the class into a injected classes list in your Module definition.

  public class SomeService extends android.app.IntentService {

   @Inject
   Synchronizer synchronizer;

   public SomeService(String name) {
     super(name);
   }

   @Override
   public void onCreate() {
     super.onCreate();
     ((YourApplication) getApplication()).inject(this);
   }

   @Override
   protected void onHandleIntent(Intent intent) {
      synchronizer.doSynch();
   }
}

Dagger 2.10+

Dagger 2.10 has introduced AndroidInjection so no further dependency on the concrete Application instance is required.

  public class SomeService extends android.app.IntentService {

   @Inject
   Synchronizer synchronizer;

   public SomeService(String name) {
     super(name);
   }

   @Override
   public void onCreate() {
     super.onCreate();
     AndroidInjection.inject(this);
   }

   @Override
   protected void onHandleIntent(Intent intent) {
      synchronizer.doSynch();
   }
}
Michal Harakal
  • 1,025
  • 15
  • 21
  • 2
    Thank you very much. It is what I searched. You're right. I can add that you need invoke .inject method inside onCreate() method. But whole idea works as charm. – lstrzelecki May 18 '14 at 10:13
  • 2
    You cant get application in constructor method. Only in onCreate. – onCreate Feb 20 '15 at 11:18
  • 4
    `getApplication` can return `null` inside constructor. If so, you can override the `onCreate` method and inject your instance here. – htulipe May 04 '15 at 14:28