본문 바로가기

Android/Handler.post()

Android Handler.post() example

안드로이드 개발자 정의 쓰레드에서 Handler.post()를 이용하여 UI 쓰레드에게 실행할 코드를 전달하는 예

UI 쓰레드는 화면을 직접 갱신할 수 있기 때문에 UI 쓰레드에게 실행할 코드를 전달할 때 그 코드 안에 화면을 갱신하는 내용을 포함하면 개발자 정의 쓰레드에서 Handler와 UI 쓰레드를 이용하여 간접적으로 화면을 갱신할 수 있다. 쓰레드가 실행할 수 있는 코드는 Runnable인터페이스 안에 있는 run() 메소드이기 때문에 코드를 전달할 때는 Runnable을 구현한 객체이어야 한다.

Handler클래스의 sendMessage(), handleMessage()를 이용하는 예제는 여기를 참조하세요

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="TextView" /> </LinearLayout>


MainActivity.java

package com.example.androidapp; import android.app.Activity; import android.graphics.Point; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.MotionEvent; import android.widget.TextView; public class MainActivity extends Activity { TextView tv; int num; Handler handler; // handleMessage()를 오버라이드할 필요가 없기 때문에 하위 클래스를 선언할 필요가 없다 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.textView1); handler = new Handler(); new Thread() { // 개발자 정의 쓰레드에서 Handler를 이용하여 UI 쓰레드에게 실행할 코드를 전달한다 public void run() { for(int i=0;i<10;i++) { handler.post( new Runnable() { public void run() { tv.setText(tv.getText().toString()+(++num)); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }; }.start(); } }