首页 > 解决方案 > Activity 在 onCreate 之后调用 onStop

问题描述

我有 3 项活动:入职活动、登录活动和第三项活动。当用户第一次打开我的应用程序时,它会在登录活动后进入引导,它会要求使用 Firebase 登录谷歌。当用户这样做时,它将开始第三个活动并完成旧的活动,如下所示:

val intent = Intent(baseContext, SkyActivity::class.java)
startActivity(intent)
finish()

但是每次用户登录并启动3rd activity,onPause()都会被调用。它使应用程序崩溃,因为我onPause()停止了我的背景歌曲:

override fun onPause() {
    super.onPause()
    if (backgroundSongService.isPlaying()) {
        backgroundSongService.pauseMusic()
    }
}

而此时,我backgroundSongService的仍然是null(我在我的 onCreate 中调用了一个初始化它的函数)。所以我得到了错误:

lateinit property backgroundSongService has not been initialized

但这只发生用户登录时。如果他在登录后关闭应用程序并再次打开,他仍然会登录。所以活动流程将是:OnboardingActivity->3rdActivity

OnboardingActivity 将像这样调用第三个活动:

if (firebaseUser != null) {
    val intent = Intent(baseContext, SkyActivity::class.java)
    startActivity(intent)
    finish()
} 

和我Intent里面的一模一样LoginActivity。但不同的是,这一次,onPause不会在第三个活动中调用。为什么它只在之后调用LoginActivity

标签: androidandroid-studiokotlinandroid-intentandroid-activity

解决方案


快速解决您的崩溃问题

使用前验证后台服务不为空

override fun onPause() {
    super.onPause()
    if (backgroundSongService!=null && backgroundSongService.isPlaying()) {
        backgroundSongService.pauseMusic()
    }
}

推荐阅读