2012년 8월 3일 금요일

안드로이드 쓰레드 6/10

사실 상 자바 쓰레드랑 안드로이드 쓰레드랑 다른 점은 거의 없다.

아버지와 아들이니까
그게 아니면
어머니와 딸?

믓튼. 안드로이드에서는 쓰레드를 어떻게 쓰는지 보자.

우선 자바 쓰레드에서 포스팅 했던 Thread, Runnable을 쓰는데

Handler 라는 넘이 추가가 되었다. 이넘은 쓰레드간에 메시지 교환을 담당한다.

자바로 비교해서 하는 일은 ExcutorService와 비슷한 녀석으로 보이는데 쓰는 방식이나 의미가 다르다.

이클립스에서 기본 안드로이드 프로젝트를 생성해서 xml이랑 java파일 내용이랑 붙여 넣으면 실행이 가능하다.


package com.example.threadtest_android;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

ProgressBar myProgress;
TextView Text01;
EditText edit01;
Button btOK;
int accum = 0;
long startingMills = System.currentTimeMillis();
boolean isRunning = false;
String str = "Data";
Handler myHandler = new Handler();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Text01 = (TextView)findViewById(R.id.textView1);
        
        myProgress = (ProgressBar)findViewById(R.id.progressBar1);
        myProgress.setMax(100);
        
        edit01 = (EditText)findViewById(R.id.editText1);
        edit01.setHint("Main Thread... Input some text");
        
        btOK = (Button)findViewById(R.id.button1);
        btOK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Editable txt = edit01.getText();
Toast.makeText(getBaseContext(), "String =" + txt, Toast.LENGTH_LONG).show();
}
});

    }
        @Override
        protected void onStart() {
        super.onStart();
        Thread myThread1 = new Thread(backgroundTask, "background"); 
//뒤에는 쓰레드 네임이다. 
        myThread1.start(); //쓰레드 시작은 똑같다. backgroundTask로 가보자.
        myProgress.incrementProgressBy(0);
        }
        
        private Runnable forgroundTask = new Runnable() {
        public void run() {
        try{
        int progressStep = 5;
        Text01.setText(str + "\nTotal sec. so far: " + (System.currentTimeMillis() - startingMills) / 1000 );
        myProgress.incrementProgressBy(progressStep);
        accum += progressStep;
        if(accum >= myProgress.getMax()) {
        Text01.setText("Background work over");
        myProgress.setVisibility(View.INVISIBLE);
        }
        }
        catch(Exception e) {
        e.printStackTrace();
        }
        }
        };
        
//얘가 실행된다.
        private Runnable backgroundTask = new Runnable() {
        public void run() {
        try {
        for(int n=0; n < 20; n++) {
        Thread.sleep(1000);
        myHandler.post(forgroundTask);
//POST 명령어는 runnable 을 인자로 받고 실행시켜 주는 일을 한다.
//Thread 없이 Thread를 start 시켜준다고 보면 되겠다.
//계속해서 forground를 실행시켜준다.

        }
        } catch(InterruptedException e) {
        e.printStackTrace();
        }
        }
        };
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
}


xml은 이렇다.
-----------------------

        xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

          android:id="@+id/linearLayout1"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical" >

                  android:id="@+id/textView1"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="TextView" />

                  android:id="@+id/progressBar1"
           style="?android:attr/progressBarStyleHorizontal"
           android:layout_width="300dp"
           android:layout_height="wrap_content" />

       






------------------------------------------------

팁으로 쓰레드 만들 때 Thread aaa = new Thread 로 안나가도 된다. 한번 쓰고 버릴거면
1/10 포스팅에서 이미 말했던거지만...

ex)

new Thread(backgroundTask, "background").start();

요렇게 바꾸어도 되고

버튼의 경우도

변수를 만들지 않고 이렇게 써도 된다(위 소스에 추가하면 추가 기능이 된다)

  findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
myProgress.setProgress(0);
accum=0;
myProgress.setVisibility(View.VISIBLE);
}
});

단순한 Handler myHandler = new Handler();

만으로 자바 쓰레드를 생성하는 방법을 알아 보았다.

댓글 없음:

댓글 쓰기

국정원의 댓글 공작을 지탄합니다.

UPBIT is a South Korean company, and people died of suicide cause of coin investment.

 UPBIT is a South Korean company, and people died of suicide cause of coin. The company helps the people who control the market price manipu...