본문 바로가기


안드로이드 


쓰레드(Thread)와 핸들러(Handler) 


사용하기



쓰레드와 핸들러란?


컴퓨터 프로그램 수행 시 프로세스 내부에 존재하는 수행 경로, 즉 일련의 실행 코드. 프로세스는 단순한 껍데기일 뿐, 실제 작업은 스레드가 담당한다. 프로세스 생성 시 하나의 주 스레드가 생성되어 대부분의 작업을 처리하고 주 스레드가 종료되면 프로세스도 종료된다. 하나의 운영 체계에서 여러 개의 프로세스가 동시에 실행되는 환경이 멀티태스킹이고, 하나의 프로세스 내에서 다수의 스레드가 동시에 수행되는 것이 멀티스레딩이다.


이라고 합니다.



우선 안드로이드 프로젝트를 만들어 줍니다.

만들것은 쓰레드를 이용한 계산기 입니다.

부족한 점이 많습니다.

그냥 참고용 입니다.



숫자 입력 후 버튼을 클릭하면 결과값이 나옵니다.



main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<EditText
android:id="@+id/fText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/sText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button
android:id="@+id/plus"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="+"/>

<Button
android:id="@+id/minus"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="-"/>

<Button
android:id="@+id/multi"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="*"/>

<Button
android:id="@+id/div"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="/"/>

</LinearLayout>

<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content" />


</LinearLayout>



MainAtivity.java


public class MainActivity extends AppCompatActivity {

EditText fText, sText;
TextView resultView;
Button plus, minus, multi, div;

int fValue, sValue;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

fText = (EditText)findViewById(R.id.fText);
sText = (EditText)findViewById(R.id.sText);

resultView = (TextView)findViewById(R.id.result);

plus = (Button)findViewById(R.id.plus);
minus = (Button)findViewById(R.id.minus);
multi = (Button)findViewById(R.id.multi);
div = (Button)findViewById(R.id.div);


plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getInt();

BackThread bThread = new BackThread(mHandler,fValue,sValue,0);
bThread.setDaemon(true);
bThread.start();
}
});

minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getInt();

BackThread bThread = new BackThread(mHandler,fValue,sValue,1);
bThread.setDaemon(true);
bThread.start();
}
});

multi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getInt();
BackThread bThread = new BackThread(mHandler,fValue,sValue,2);
bThread.setDaemon(true);
bThread.start();
}
});

div.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fValue = Integer.parseInt(fText.getText().toString());
sValue = Integer.parseInt(sText.getText().toString());

BackThread bThread = new BackThread(mHandler,fValue,sValue,3);
bThread.setDaemon(true);
bThread.start();
}
});


}

Handler mHandler = new Handler(){
public void handleMessage(Message message){
if(message.what==0){
resultView.setText("result : " + message.arg1);
}
}
};

public void getInt(){
fValue = Integer.parseInt(fText.getText().toString());
sValue = Integer.parseInt(sText.getText().toString());
}

}


핸들러는 값을 받는 쪽에 위치해야 합니다.


BackThread.java

public class BackThread extends Thread {
int fValue = 0;
int sValue = 0;
int resultValue = 0;

int commandValue = 0;
Handler mHandler;

public BackThread(Handler m, int f, int s, int commandValue){
this.mHandler = m;
this.fValue = f;
this.sValue = s;
this.commandValue = commandValue;
}
public void run() {
switch (commandValue) {
case 0:
resultValue = fValue + sValue;
break;
case 1:
resultValue = fValue - sValue;
break;
case 2:
resultValue = fValue * sValue;
break;
case 3:
resultValue = fValue / sValue;
break;
}

Message m = new Message();
m.what = 0;
m.arg1 = resultValue;

mHandler.sendMessage(m);
}
}

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

더 좋은 방법이 많이 있습니다. 참고만 하시기 바랍니다.

쓰레드에서 다 받는게 아니라 Handler에 what 값을 변경하여 메인에서 건들여준다던가

RunOnUiThread 를 사용하거나 AsyncTask 를 이용하는 방법도 있습니다.


엉망진창

개인 블로그 입니다. 코딩, 맛집, 정부정책, 서비스, ~방법 등 다양한 정보를 소개합니다