1

I am using Hilt for dependency injection, and I wanted to start a singleton Android Service (DeviceConnectionService), and be able to access that Service object to do something to it

I observed 2 instances of DeviceConnectionService being created even though it was denoted as Singleton. Any idea or advice on this? Thanks in advance!

Following is my code setup:

Android Library: DeviceLibrary

Android Service

@AndroidEntryPoint
@Singleton
public class DeviceConnectionService extends Service {
    @Inject
    public DeviceConnectionService () {
        Timber.d("DEVICE connection : " + hashCode());
    }
}

Another classes that wants to be injected with the Android Service - to do something:

@Singleton
public class Connection implements IHololensConnection {

    @Inject
    DeviceConnectionService connectionService;
    ...
}

App

MainActivity.java

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {
...

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ...
        Intent intent = new Intent(getApplicationContext(), DeviceConnectionService.class);
        startService(intent);
    }
...
}

1 Answers1

1

Dagger doesn't start services, it just injects them once Android starts them. If you're observing that your Service is instantiated multiple times, that's unrelated to Hilt/Dagger/@Singleton: You'll need to ensure that your Service doesn't stop itself, and that nothing else stops it.

(This would be slightly different if your Service were instantiated exactly once, and objects that your Service injects were instantiated more times than you wanted. In that case you would need to put the @Singleton annotation on your binding for that class in a Module. However, that only applies to objects that Dagger creates, which excludes Service, Activity, or anything else marked with @AndroidEntryPoint.)

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251