本文介绍了startActivity跳过onCreate()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的案例Activity1 -> Activity2.

过去,当我使用startActivity(Intent(this, Activity2::class.java))时,没有任何问题,并且会调用Activity2onCreate()方法.

In the past when I've used startActivity(Intent(this, Activity2::class.java)) there have been no issues and the onCreate() method of Activity2 would be called.

在我目前的情况下,这没有发生.我在onCreate()方法中有日志,但它们从未被命中.但是,如果我创建一个onStart()方法,它将进入那里.但是,在应用程序的生存期内,从未在Activity2中的onCreate()中被击中.这怎么可能. onCreate是我认为onStart之前的要求.

In my current case this is not happening. I have logs in the onCreate() method and they are never hit. But if I create a onStart() method it enters there. However, never in my logs for the lifetime of the application does onCreate() of Activity2 ever get hit. How is this possible. onCreate is a requirement before onStart I thought.

这是我上面引用的实际代码.

Here is the actual code I'm referencing above.

class Activity1 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Timber.d("onCreate")

        setContentView(R.layout.activity_splash)

        startActivity(Activity2.getIntent(this))
    }
}

class Activity2 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        Timber.d("onCreate") // Never gets touched
    }

    override fun onStart() {
        super.onStart()
        Timber.d("onStart"); // Is hit with no problems.
    }

    companion object {
        fun getIntent(@NonNull context: Context) : Intent {
            return Intent(context, Activity2::class.java)
        }
    }
}

推荐答案

您覆盖了错误的onCreate-您不想使用PersistableBundle版本.将您的onCreate更改为仅采用savedInstanceState: Bundle?参数:

You overrode the wrong onCreate - you do not want to use the PersistableBundle version. Change your onCreate to only take the savedInstanceState: Bundle? parameter:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Timber.d("onCreate") // Now it'll be called
}

这篇关于startActivity跳过onCreate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 15:02