Mingdi
Mingdi

Reputation: 185

How can I start a new activity in a coroutine? Kotlin Android

I have a coroutine in my app that will start a new activity after a delay like so:

GlobalScope.launch() { 
   delay(1000L)
   startActivity(Intent(this, ThisActivity::class.java))
}

However I get an error on intent saying that "none of the following functions can be called with the arguments supplied"

How can I fix this? Thanks

Upvotes: 3

Views: 4609

Answers (1)

Francesc
Francesc

Reputation: 29330

The problem is that this refers to the CoroutineScope:

GlobalScope.lauch(){
   delay(1000L)
   startActivity(Intent(this,ThisActivity::class.java))
}

you need to specify the context here. If you are running this in an Activity (say, MyActivity), you could do like so

GlobalScope.lauch(Dispatchers.Main) {
   delay(1000L)
   startActivity(Intent(this@MyActivity,ThisActivity::class.java))
}

Upvotes: 11

Related Questions