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();
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With