프로그래밍/안드로이드

안드로이드 핸들러로 UI처리하고 쓰레드에서 실작업 처리하기

가카리 2012. 8. 23. 21:25
반응형

이번에는 쓰레드와 핸들러 동시에 이용해서 구현해봅시다.

 

쓰레드에서 실제 작업만 처리하고 UI 관련 작업은 핸들러에게 메시지를 보내서 다 처리합니다.

 

main.xml

 

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

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical"

    >

 

    <TextView

        android:id="@+id/text"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerHorizontal="true"

        android:layout_centerVertical="true"

        android:text="@string/hello_world"

        tools:context=".MainActivity" />

    <Button

       android:id="@+id/btn"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:text="Update"

        >

       

       

    </Button>

 

</LinearLayout>

 

 

MainActivity.java 파일

 

package com.example.longtime4;

 

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.app.Activity;

import android.app.Dialog;

import android.app.ProgressDialog;

import android.content.DialogInterface;

import android.view.Menu;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

 

public class MainActivity extends Activity {

 

           int mValue;

           TextView mText;

           ProgressDialog mProgress;

           boolean mQuit;

           UpdateThread mThread;

          

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

       

        mText=(TextView)findViewById(R.id.text);

        Button btnUpdate =  (Button)findViewById(R.id.btn);

        btnUpdate.setOnClickListener(new View.OnClickListener() {

                               

                                @Override

                                public void onClick(View v) {

                                          // TODO Auto-generated method stub

                                          mValue = 0;//값 초기화

                                          showDialog(0);//dialog 보여줌. 넘기는 값은 id

                                          mQuit  = false;

                                          mThread = new UpdateThread();

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

                                         

                                }

                     });

       

       

    }

   

 

    @Override

           protected Dialog onCreateDialog(int id) {

                     // TODO Auto-generated method stub

        

         switch(id){

                    case 0 :

                              mProgress = new ProgressDialog(this);//다이얼로그 만들고

                              mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

                              mProgress.setTitle("Updating");

                              mProgress.setMessage("Wait...");

                              mProgress.setCancelable(false);

                              mProgress.setButton("Cancel", new DialogInterface.OnClickListener() {

                                                    

                                         //리스너 등록

                                                     @Override

                                                     public void onClick(DialogInterface dialog, int which) {

                                                                // TODO Auto-generated method stub

                                                                mQuit = true;//flag 값을 바꿈.

                                                                dismissDialog(0);//다이럴로그 없앰

                                                     }

                                          });

                             

                              return mProgress;

         }

        

                     return null;

           }

 

    Handler mHandler = new Handler(){

         //메시지받으면 여기서 처리

                    public void handleMessage(Message msg){

                              mValue = msg.arg1;

                              mText.setText(Integer.toString(mValue));//이부분은 run메소드에서 돌리면 에러남.

                             

                              if(mValue < 100){

                                         mProgress.setProgress(mValue);

                              }else{

                                         mQuit = true;

                                         dismissDialog(0);

                              }

                    }

    };

   

    class UpdateThread extends Thread{

 

         //쓰레드 시작시 여기로 옴.

                     @Override

                     public void run() {

                                // TODO Auto-generated method stub

                               

                                while(mQuit == false){//flag값으로 판단함. cancel버튼이 눌렸는지 아닌지.

                                          mValue++;//값 올리고

                                          Message msg = mHandler.obtainMessage();//메시지에 값 넣기위해 메시지 가져옴

                                          msg.arg1 = mValue;//값 넣음

                                          mHandler.sendMessage(msg);//핸들러로 값 보냄

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

                                }

                     }

   

    }

 

           @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);

        return true;

    }

}

 

 

반응형