프로그래밍/안드로이드

안드로이드 쓰레드 구현 2번째 방법 post 메소드를 이용하자.

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

쓰레드 두번째 post메소드에 인자로 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="증가"

/>

</LinearLayout>

 

 

자바파일

 

package com.android.ex91;

 

import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.view.View;

import android.widget.TextView;

 

public class ex91 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() {//run 오버라이딩함

                    while (true) {

                           mBackValue++;

                          

                           //이전예제에서는 sendEmptyMessage(0)이었으나 지금 이렇게 바뀜

                           mHandler.post(new Runnable() {//Runnable 인터페이스를 구현하는 방법 post메소드의 인자로 넘김

                                 public void run() {

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

                                 }

                           });

                           try {

                                

                                 Thread.sleep(1000);

                          

                           } catch (InterruptedException e) {;}

                    }

             }

       }

 

       Handler mHandler = new Handler();//핸들러 객체 선언후 handleMessage메소드를 오버라이딩 하는게 아님

}

 

 

반응형