androidkotlinkoinandroid-service-binding

How to use koin for Service


I was starting the foreground service by manually binding and then using its method.

However, I recently came across Koin and found https://insert-koin.io/docs/reference/koin-compose/compose

@Composable
fun App(myService: MyService = koinInject()) {
}

Now, This gave me the idea that Koin would do the binding for me, and I'll be able to use the method of the Service directly without binding and unbinding of service using ServiceConnection

But, I get,

java.lang.NullPointerException: class name is null

On startForeground call inside service.

and,

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

On, any super member call.

Now, either I'm not properly setting up Koin, or Koin doesn't support Service (even if I manually bind it, but use the service instance from Koin it still crashes with the same issue).

I'd like experts' opinions here, cuz the docs mention MyService, but not being able to use SuperClass 'Service' member seems like that was a poor choice for a class name.


Solution

  • The example of MyService in koin docs is not an android service, its a service that holds business logic. service, usecases are interchangeable names for domain layer class that holds business logic in clean architecture. You can bind your android service in just a traditional way.