프로그래밍/안드로이드

안드로이드 쓰레드 첫번째 예제 handleMessage 구현하는 방법

가카리 2012. 8. 21. 21:03
반응형

쓰레드

 

자바에서 쓰레드를 구현하는 방법 2가지가 있는데 Thread클래스를 상속받는 방법과 Runnable인터페이스를 구현하는 방법 2가지가 있습니다.

 

그중 Runnable인터페이스를 구현하는 방법으로 한번 해보았습니다.

 

그러나 코드상에 문제가 있습니다. 그 문제는 코드에 써놨습니다.

 

main.xml

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

> 

<TextView

android:id="@+id/mainvalue"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textSize="20sp"

android:text="MainValue : 0"

/>

<TextView

android:id="@+id/backvalue"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textSize="20sp"

android:text="BackValue : 0"

/>

<Button

android:id="@+id/increase"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="mOnClick"

android:text="Increase"

/>

</LinearLayout>

 

 

자바파일

 

package com.android.ex89;

 

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

 

 

public class ex89 extends Activity {

       int mMainValue = 0;

       int mBackValue = 0;

       TextView mMainText;

       TextView mBackText;

 

       public void onCreate(Bundle savedInstanceState) {

             super.onCreate(savedInstanceState);

             setContentView(R.layout.main);

 

             mMainText = (TextView)findViewById(R.id.mainvalue);

             mBackText = (TextView)findViewById(R.id.backvalue);

            

             BackRunnable runnable = new BackRunnable();

             Thread thread = new Thread(runnable);

             thread.setDaemon(true);

             thread.start();

       }

      

       public void mOnClick(View v) {

             mMainValue++;

             mMainText.setText("MainValue : " + mMainValue);

             mBackText.setText("BackValue : " + mBackValue);

       }

 

       class BackRunnable implements Runnable {

             public void run() {

                    while (true) {

                           mBackValue++;

                           mBackText.setText("BackValue : " + mBackValue);// 부분에서 뻗는다

                           //문법적으로는 맞지만 객체를 쓰레드가 동시에 변경하는 것을 허용하면

                           //복잡해지기 때문이다.

                           try { Thread.sleep(1000); } catch (InterruptedException e) {;}

                    }

             }

       }

}

 

 

 

 

안드로이드에서 쓰레드는 Handler클래스에서 handleMessage메소드를 구현하는 것으로 할 수 있습니다.. (자바에서는 Runnable 인터페이스를 상속받고 run메소드를 구현함)

 

여기서 Message 객체가 나옵니다

 

Message객체의 멤버변수는

 

int what 메세지의 의미를 설명함.

int arg1 메시지의 추가정보

int arg2 메시지의 추가정보

Object obj 정수만으로 메시지를 기술 할 수 없을 때 임의의 객체를 보낸다.

Messenger replyTo 메시지에 대한 응답을 받을 객체를 지정한다.

 

전달하고자 하는 내용을 위의 메시지 Message객체에 저장하여 핸들러로 전송합니다.

 

이때 다음 메소드를 사용합니다..

 

sendMessage()메소드 넘겨받은 메시지를 즉시 메시지큐의 맨뒤에 쌓는다

 

sendEmptyMessage()메소드 sendMessage와 비슷하나 아무메시지도 보내지않는다.

 

sendMessageAtFrontOfQueue()메소드 넘겨받은 메소드를 메시지큐를 맨 앞에 쌓는다

 

sendMessageAtTime()메소드 넘겨받은 메소드를 특정 시각이 되면 메시지 큐에 쌓는다.

 

sendMessageDelayed()메소드 넘겨받은 메소드를 특정 시간이 지난 이후에 메시지큐에 쌓는다.

 

그래서 위의 예제를 다음과 같이 바꿀 수 있습니다.

 

main.xml

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

> 

<TextView

android:id="@+id/mainvalue"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textSize="20sp"

android:text="MainValue : 0"

/>

<TextView

android:id="@+id/backvalue"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textSize="20sp"

android:text="BackValue : 0"

/>

<Button

android:id="@+id/increase"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="mOnClick"

android:text="증가"

/>

</LinearLayout>

 

package com.android.ex90;

 

import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.widget.TextView;

 

 

public class ex90 extends Activity {

       int mMainValue = 0;

       int mBackValue = 0;

       TextView mMainText;

       TextView mBackText;

 

       public void onCreate(Bundle savedInstanceState) {

             super.onCreate(savedInstanceState);

             setContentView(R.layout.main);

 

             mMainText = (TextView)findViewById(R.id.mainvalue);

             mBackText = (TextView)findViewById(R.id.backvalue);

             BackThread thread = new BackThread();

             thread.setDaemon(true);//데몬쓰레드로 설정

             //메인 쓰레드가 종료되면 쓰레드도 바로 종료됨 종속성을 가지게

             thread.start();//쓰레드 시작

       }

 

       public void mOnClick(View v) {

             mMainValue++;

             mMainText.setText("MainValue : " + mMainValue);

       }

 

       class BackThread extends Thread {//이번에는 Thread클래스를 상속받는 방법으로 쓰레드를 구현함

             public void run() {

                    while (true) {

                           mBackValue++;

                           mHandler.sendEmptyMessage(0);//int what = 0

                           try {

                                

                                 Thread.sleep(1000); //1초마다 메시지를 계속 보내게

                                

                           } catch (InterruptedException e) {;}

                    }

             }

       }

 

       Handler mHandler = new Handler() {//핸들러 객체를 만들고

             public void handleMessage(Message msg) {

                    //handleMessage메소드를 구현하는 것으로 쓰레드를 만들 있음

                    if (msg.what == 0) {//sendEmptyMessage에서 what 의미함

                           mBackText.setText("BackValue : " + mBackValue);

                    }

             }

       };

}

 

 

 

반응형