Search code examples
kotlinandroid-activitycoroutine

Activity is launched twice when starting from Coroutine


I'm using a SplashActivity, to prepare some data on my app', then redirect to my MainActivity.

I do this in a coroutine, to use some database transactions.

If I start the MainActivity from inner the coroutine, it's started twice (When pressing "return" button, it closes the MainActivity and show a second MainActivity behind). If I start the MainActivity from outside the coroutine, it works (When pressing "return" button, it closes the MainActivity and the app')

A simple example of the SplashActivity :

class SplashActivity : AppCompatActivity() {
    private lateinit var activityScope: CoroutineScope
    private lateinit var image: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        prepareApplication()
    }

    override fun onPause() {
        activityScope.cancel()
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        prepareApplication()
    }

    private fun prepareApplication() {
        activityScope = CoroutineScope(Dispatchers.Main)
        activityScope.launch {
            // This starts the MainActivity twice
            startActivity(Intent(this@SplashActivity, MainActivity::class.java))
            finish()
        }
        // This starts the MainActivity once
        // startActivity(Intent(this@SplashActivity, MainActivity::class.java))
        // finish()
    }
}

Do you know why and how to avois this ?

Thanks !


Solution

  • You are calling this function from both onCreate and onResume and since launch does not execute immediately, both startActivity calls added to main thread queue. In the second case when you do not use launch, it is immediately executed and thus second call could not happened.