Android Handler, Looper, MessageQueue 완벽 정리

✨ 개요

Android에서 메인 스레드(UI Thread) 또는 워커 스레드 간의 작업을 안전하게 처리하기 위해 Handler, Looper, MessageQueue가 긴밀히 협력합니다. 이들은 메시지 기반의 비동기 작업 처리를 가능하게 하는 핵심 컴포넌트입니다.


1. 📦 각 구성요소의 역할

// 예: 메인스레드에서 실행
val handler = Handler(Looper.getMainLooper())
handler.post {
    Log.d("TAG", "이 코드는 메인 스레드에서 실행됩니다")
}

2. ✅ 공통점과 차이점


3. 🧪 샘플 코드: 워커 스레드에서 Looper 사용

class WorkerThread : Thread() {
    lateinit var handler: Handler

    override fun run() {
        Looper.prepare()

        handler = Handler(Looper.myLooper()!!) {
            Log.d("WorkerThread", "Message received on worker thread")
            true
        }

        Looper.loop()
    }
}

val thread = WorkerThread()
thread.start()

// 메인스레드에서 메시지 전송
thread.handler.post {
    Log.d("Main", "메시지 전송 완료")
}

4. 🧾 결론



Related Posts