본문 바로가기

Android

[안드로이드]쓰레드와 핸들러

쓰레드란?

쓰레드는 하나의 프로세스내에서 실행되는 작업의 단위를 말한다.

 하나의 운영 체계에서 여러 개의 프로세스가 동시에 실행되는 환경이 멀티태스킹이고, 하나의 프로세스 내에서 다수의 스레드가 동시에 수행되는 것이 멀티스레딩이다.


핸들러란?

안드로이드에서는 화면UI에 접근하는 것을 막아두고 실행시 생성되는 메인 스레드를  통해서만 화면 UI를 변경할 수 있기 때문에 핸들러를 통해서 메인 쓰레드에 접근하여 UI를 수정한다.


핸들러는 1.메시지처리 방식 과 2. Runable객체 실행방식이 있다.

1. 메시지처리 방식


1. 핸들러를 정의한다.

public class MainActivity extends ActionBarActivity {

/**
* 프로그레스바
*/
ProgressBar bar;
TextView textView01;
boolean isRunning = false;

/**
* 메인 스레드의 UI에 접근하기 위한 핸들러
*/
ProgressHandler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

bar = (ProgressBar) findViewById(R.id.progress);
textView01 = (TextView) findViewById(R.id.textView01);

handler = new ProgressHandler();

}

핸들러를 상속받은 클래스

public class ProgressHandler extends Handler {

public void handleMessage(Message msg) {

bar.incrementProgressBy(5);

if (bar.getProgress() == bar.getMax()) {
textView01.setText("Done");
} else {
textView01.setText("Working ..." + bar.getProgress());
}

}

}


2. 스레드를 생성한다.

Thread thread1 = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 20 && isRunning; i++) {
Thread.sleep(1000);

Message msg = handler.obtainMessage();
handler.sendMessage(msg);
}
} catch (Exception ex) {
Log.e("SampleThreadActivity", "Exception in processing message.", ex);
}
}
});

run() 메소드에 쓰레드 실행시 수행할 소스를 적고


thread1.start();

start()메소드를 호출하면 쓰레드의 run이 수행하기 시작한다.

run에서는 먼저 obtainMessage()메서드로 메시지 객체를 리턴받고 sendMessage()메서드로 메시지 큐에 넣는다.

메시지 큐에 들어간 메시지는 순서대로 핸들러가 처리함 이 때, handleMessage()메소드에 정의된 기능이 수행된다.

public class ProgressHandler extends Handler {

public void handleMessage(Message msg) {

bar.incrementProgressBy(5);

if (bar.getProgress() == bar.getMax()) {
textView01.setText("Done");
} else {
textView01.setText("Working ..." + bar.getProgress());
}

}

}

핸들러의 handleMessage()메소드 내용 


1. Runable 객체 실행방식

1. Runable 인터페이스를 implements하여 핸들러를 구현한다.

public class ProgressRunnable implements Runnable {

public void run() {

bar.incrementProgressBy(5);

if (bar.getProgress() == bar.getMax()) {
textView01.setText("Runnable Done");
} else {
textView01.setText("Runnable Working ..." + bar.getProgress());
}

}

}


2. 스레드를 구현한다.

Thread thread1 = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 20 && isRunning; i++) {
Thread.sleep(1000);

handler.post(runnable);
}
} catch (Exception ex) {
Log.e("SampleThreadActivity", "Exception in processing message.", ex);
}
}
});

똑같이 start()메소드로 실행시켜주면 run()메소드가 호출되고 핸들러객체의 post()메서드에 의해 Runable 객체의 run()이 수행된다.