我想将一个类注入到扩展FirebaseMessagingService
的服务中,但据我所知,为了在服务类中注入内容,该服务应该扩展DaggerService()
。
这就是我尝试过的
@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
}
服务类
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
}
}
但是上面的代码无法正常工作,因为我得到
kotlin.UninitializedPropertyAccessException: lateinit property parser has not been initialized
解决了!您需要做的就是在onCreate
内部和呼叫超级之前呼叫AndroidInjection.inject(this)
。这将手动注入 FCM 服务类,因为我们无法使其扩展DaggerService
应该为我们完成这项工作。