안드로이드/Thread

안드로이드 RunOnUiThread

김어찐 2022. 6. 16. 11:58
728x90

RunOnUiThread 메서드는 개발자가 발생시킨 일반 쓰래드에서 코드 일부를 Main Thread가 처리하도록 하는 메서드이다.
이를 이용해 Handler 대신하여 Thread를 운영할 수 있다.

 

package com.example.runonuithread

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {
    var isRunning = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
            val now = System.currentTimeMillis()
            textView.text = "버튼 클릭 ; $now"
        }

        isRunning= true
        thread {
            while (isRunning) {
                SystemClock.sleep(500)
                val now2 = System.currentTimeMillis()
                Log.d("test","thread: $now2")

//                // 메인 스레드가 실행
//                runOnUiThread(object : Thread() {
//                    override fun run() {
//                        textView2.text = "runOnUiThread : $now2"
//                    }
//                })
                runOnUiThread {
                    textView2.text = "runONUiTHread : $now2"
                }

                SystemClock.sleep(500)

                // 메인 스레드가 실행
                runOnUiThread(object : Thread() {
                    override fun run() {
                        textView2.text = "또다른 작업업"
                   }
                })
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        isRunning = false
    }
}

 

728x90