如何使用Koin将类注入MainActivity



我想创建一个Splash屏幕,并在用户的身份验证状态确定后显示它。我有一个名为AuthStateController的全局singleton,它保存我的状态和一些额外的函数
但由于installSplashScreen函数不在可组合的范围内,我无法使用Koin注入AuthStateController类来访问我的loading状态。

下面是我所有Koin模块的主要活动。以及CCD_ 6函数。

class MainActivity : ComponentActivity() {
// not allowed because outside of Composable
private val authStateController: AuthStateController by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startKoin {
androidLogger(if (BuildConfig.DEBUG) Level.ERROR else Level.NONE)
androidContext(this@MainActivity)
modules(listOf(appModule, networkModule, viewModelModule, interactorsModule))
}
installSplashScreen().apply {
setKeepVisibleCondition {
// need AuthStateController instance to determine loading state
authStateController.state.value.isLoading
}
}
setContent {
M3Theme {
SetupNavGraph()
}
}
}
}
}

这是Koinmodule,它提供了我的AuthStateController类:

val appModule = module {
single { AuthStateController(get()) }
}

这是我的AuthStateController类,它保存了我的状态和一些额外的函数:

class AuthStateController(
private val getMeInterceptor: GetMeInterceptor
) {
val state: MutableState<AuthState> = mutableStateOf(AuthState())
fun fetchMe() {
val me = getMeInterceptor.execute().collect(CoroutineScope(Dispatchers.IO)) { dataState ->
dataState.data?.let {
state.value =
state.value.copy(profile = it, isAuthenticated = true, isLoading = false)
}
}
}
init {
val token = settings.getString(Constants.AUTH_TOKEN)
if (token.isNotBlank()) {
fetchMe()
state.value = state.value.copy(authToken = token)
}
}
}

如何访问在MainActivity中使用Koin创建的singleton,并在installSplashScreen函数中使用它?

编辑

Android清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.sessions_clean.android">
<uses-permission android:name="android.permission.INTERNET" />

<application
// app crashes when adding line below
android:name=".MainApplication"
android:allowBackup="false"
android:supportsRtl="true"
android:theme="@style/Theme.App.Starting"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true"
android:theme="@style/Theme.App.Starting">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

当我将android:name添加到现有的应用程序标签时,应用程序会立即崩溃。

但是,当我为新的MainApplication创建新的应用程序标签时,我在IDE中会遇到类似Attribute android:allowBackup is not allowed here的错误

我认为您可以在Application中使用startKoin

MainApplication.kt

class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
...
}

}
}

AndroidManifest.xml

<manifest ...>
<application
android:name=".MainApplication"
...>
...
</application>
</manifest>

最新更新