본문 바로가기

Study/Programming

안드로이드 스레드 AsyncTask 사용

꺅


안드로이드 프로세스와 스레드


스레드에서 UI를 조작하는 방법 중 하나인 AsyncTask 클래스를 사용한 예제입니다


AsyncTask 클래스는 사용자 인터페이스에 대한 비동기적 작업을 허용합니다


작업 스레드 안에서 주어진 작업을 실행하며 결과를 UI 스레드를 전달하지요


따라서 UI스레드부분과 작업스레드부분 2가지를 모두 가지고 있는 스레드입니다





AsyncTask클래스

  • AsyncTask 는 반드시 UI 스레드에서 생성되며 딱 한 번만 실행
  • <Params, Progress, Result>와 같이 제네릭을 이용해 작성

(필요하지 않은 타입은 void라고 표시)

  • doInBackground() 는 UI 스레드가 아닌 별도의 스레드에서 실행되며 작업스레드에서 자동적으로 실행
  • onPreExcute() / onPostExcute() 그리고 onProgressUpdate() 는 모두 UI 스레드에서 호출
  • doInBackground() 의 결과 값은 onPostExcute() 로 전달



AsyncTask.java

package com.example.test;


import android.app.Activity;

import android.os.AsyncTask;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.ProgressBar;


public class MainActivity extends Activity {

private ProgressBar mProgress;

private int mProgressStatus = 0;


public void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

mProgress = (ProgressBar) findViewById(R.id.progress_bar);

Button button = (Button) findViewById(R.id.Button);

button.setOnClickListener(new Button.OnClickListener(){

public void onClick(View v){

new CounterTask().execute(0);

}

});

}

class CounterTask extends AsyncTask<Integer, Integer, Integer>{

protected void onPreExecute(){}

protected Integer doInBackground(Integer... value){

while (mProgressStatus < 100){

try { Thread.sleep(1000);;

} catch( InterruptedException e){

}

mProgressStatus++;

publishProgress(mProgressStatus);

}

return mProgressStatus;

}

protected void onProgressUpdate(Integer... value){

mProgress.setProgress(mProgressStatus);

}

protected void onPostExecute(Integer result){

mProgress.setProgress(mProgressStatus);

}

}

}






main.xml

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

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

    android:id="@+id/container"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="com.example.test.MainActivity"

    tools:ignore="MergeRootFrame" >


    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:orientation="vertical" >


        <ProgressBar

            android:id="@+id/progress_bar"

            style="?android:attr/progressBarStyleHorizontal"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content" />


        <Button

            android:id="@+id/Button"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Conter Start" />



    </LinearLayout>


</FrameLayout>







실행화면

Conter Start 버튼을 클릭시

프로그레스바가 차오르는 것을 볼 수 있음





부르르2  부르르2

읽어주셔서 감사합니다 ^^*