简体   繁体   English

如何在协程中开始新的活动? Kotlin Android

[英]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"但是,我收到一个意图错误,提示“使用提供的 arguments 不能调用以下任何函数”

How can I fix this?我怎样才能解决这个问题? Thanks谢谢

The problem is that this refers to the CoroutineScope :问题是this指的是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如果您在 Activity(例如 MyActivity)中运行它,您可以这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM