Android CoroutineScope Dispatchers.Main主线程delay,kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.Button
import android.widget.Toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
companion object {
var TAG = "fly"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//点击按钮正常弹出Toast
findViewById<Button>(R.id.button).setOnClickListener(object : OnClickListener {
override fun onClick(v: View?) {
Toast.makeText(
applicationContext,
TAG + " @${Thread.currentThread().id}",
Toast.LENGTH_SHORT
).show()
}
})
Log.d(TAG, "1 @${Thread.currentThread().id}")
CoroutineScope(Dispatchers.Main).launch {
delay(20_000)
var id = Thread.currentThread().id
Log.d(TAG, "launch @$id")
}
Log.d(TAG, "2 @${Thread.currentThread().id}")
}
}
kotlin协程coroutineScope_zhangphil的博客-CSDN博客coroutineScope 创建独立协程作用域,直到所有启动的协程都完成后才结束自己。runBlocking 和 coroutineScope 很像,它们都需要等待内部所有相同作用域的协程结束后才会结束自己。两者主要区别是: runBlocking 阻塞当前线程,而 coroutineScope不会,coroutineScope会挂起并释放底层线程供其它协程使用。kotlin协程coroutineScope。https://blog.csdn.net/zhangphil/article/details/129265638