btnRestart를 누르면 쓰레드를 다시 시작합니다.
그런데 버튼을 누른 만큰 쓰레드가 생성되는거 같습니다. 쓰레드를 종료하고 싶은데 어떻게 해야하나요?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.game)
baseLayout = findViewById(R.id.baseLayout)
imgGame = findViewById(R.id.imgGame)
imgR = findViewById(R.id.imgR)
imgS = findViewById(R.id.imgS)
imgP = findViewById(R.id.imgP)
btnRestart = findViewById(R.id.btnRestart)
var win = 0
handler = object : Handler(mainLooper){
override fun handleMessage(msg: Message) {
when(msg.what){
MSG_A->{
imgGame.setImageResource(R.drawable.p)
win=1
}
MSG_B->{
imgGame.setImageResource(R.drawable.r)
win=2
}
MSG_C->{
imgGame.setImageResource(R.drawable.s)
win=3
}
}
}
}
btnRestart.setOnClickListener {
btnRestart.setText("다시하기")
runThread()
}
imgR.setOnClickListener {
if(win==1) {
count = 3
Toast.makeText(applicationContext, "졌어요", Toast.LENGTH_SHORT).show()
}
if(win==2) {
count = 3
Toast.makeText(applicationContext, "비겼어요", Toast.LENGTH_SHORT).show()
}
if(win==3) {
count = 3
Toast.makeText(applicationContext, "이겼어요", Toast.LENGTH_SHORT).show()
}
}
imgS.setOnClickListener {
if(win==1) {
count = 3
Toast.makeText(applicationContext, "이겼어요", Toast.LENGTH_SHORT).show()
}
if(win==2) {
count = 3
Toast.makeText(applicationContext, "졌어요", Toast.LENGTH_SHORT).show()
}
if(win==3) {
count = 3
Toast.makeText(applicationContext, "비겼어요", Toast.LENGTH_SHORT).show()
}
}
imgP.setOnClickListener {
if(win==1) {
count = 3
Toast.makeText(applicationContext, "비겼어요", Toast.LENGTH_SHORT).show()
}
if(win==2) {
count = 3
Toast.makeText(applicationContext, "이겼어요", Toast.LENGTH_SHORT).show()
}
if(win==3) {
count = 3
Toast.makeText(applicationContext, "졌어요", Toast.LENGTH_SHORT).show()
}
}
runThread()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
var mInflater = menuInflater
mInflater.inflate(R.menu.menu,menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
super.onOptionsItemSelected(item)
when(item.itemId){
R.id.coin ->{
var intent = Intent(this,Coin::class.java )
startActivity(intent)
finish()
return true
}
R.id.RSP ->{
var intent = Intent(this,Game::class.java )
startActivity(intent)
finish()
return true
}
}
return false
}
private fun runThread(){
count=0
newThread = Thread(object : Runnable {
override fun run(){
while(true){
if(count==3)
newThread.interrupt()
val message = handler.obtainMessage()
if(count==0){
message.what = MSG_A
handler.sendMessage(message)
sleep(1000)
count++
}else if(count==1){
message.what = MSG_B
handler.sendMessage(message)
sleep(1000)
count++
}else if(count==2) {
message.what = MSG_C
handler.sendMessage(message)
count=0
sleep(1000)
}
}
}
})
newThread.start()
}