Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger - android.app.IntentService with @Inject

Tags:

android

dagger

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();
}

}

like image 255
lstrzelecki Avatar asked Apr 24 '14 12:04

lstrzelecki


1 Answers

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();
   }
}
like image 148
Michal Harakal Avatar answered Oct 29 '22 09:10

Michal Harakal