1

I want to inject a class into a Service that extends FirebaseMessagingService but as far as I know, in order to inject stuff in a Service class that service should extends DaggerService().

This is what I tried

@Singleton
@Component(
    modules = [
        AndroidSupportInjectionModule::class, // Default module, always on top
        AppModule::class,
        ServiceBuilderModule::class
    ]
)
interface AppComponent : AndroidInjector<App> {

    // Override the builder
    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: Application): Builder

        fun build(): AppComponent

    }

}


@Module
abstract class ServiceBuilderModule {

    @ContributesAndroidInjector
    abstract fun contributeFirebaseCloudMessaging(): CloudMessaging

}

The service class

class CloudMessaging : FirebaseMessagingService() {


    @Inject
    lateinit var parser: JsonParser

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)


        val msgData = parser.fromJsonString<CommonNotification>(remoteMessage.data.toString(), CommonNotification::class.java)
            ?: return

    }

}

But the above code is not working as I am getting

kotlin.UninitializedPropertyAccessException: lateinit property parser has not been initialized
Bitwise DEVS
  • 2,858
  • 4
  • 24
  • 67
  • You've marked `parser` with `@Inject`, I don't see any provider for `JsonParser`. – Darshan Jul 30 '22 at 07:06
  • @DarShan I did not include it since that is working perfectly in other class except when using it inside a `FirebaseMessagingService`. So I need you to trust me on that part :) – Bitwise DEVS Jul 30 '22 at 07:14

1 Answers1

1

Solved! All you need to do is call AndroidInjection.inject(this) inside onCreate and before its call to super. This will manually inject the FCM Service class since we can't make it extend DaggerService which supposed to do that job for us.

Bitwise DEVS
  • 2,858
  • 4
  • 24
  • 67