使不同Thread溝通的機制,將Thread要傳遞的訊息放入Message類別,透過Handler與另一個Thread溝通,讓另一個Thread從類別取得訊息
class MainActivity : AppCompatActivity(){
//Step1:建立Handler物件接受訊息
private val handler = Handler(Looper.getMainLooper()) { msg ->
when (msg.what) { //判斷msg的編號
1 -> {
//執行於Main Thread
}
}
return@Handeler true
}
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Thread{
//執行於Background Thread
//Step2:建立Message物件並加入編號
val msg = Message()
msg.what = 1
//Step3:透過sendMessage傳送訊息
handler.sendMessage(msg)
}.start()
}
}