본문 바로가기
Smart Device/Android

Thread - Java의 Thread를 사용

by 언덕너머에 2015. 7. 30.

- activity_main.xml

Thread를 실행시킬 Start 버튼과 실행중인 쓰레드에서 값을 가져올 Get 버튼, 그리고 그 값을 보여줄 TextView

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

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

android:layout_width="match_parent"
android:layout_height="match_parent"  

android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"  tools:context=".MainActivity">

<Button android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:text="Start"/>

<Button android:id="@+id/btnGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_below="@id/btnStart"
android:text="Get"/>

<TextView android:id="@+id/txtValue"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />


</RelativeLayout>


MainActivity

자바의 표준 쓰레드를 사용해서 구현

package kr.co.devinside.myjavathread;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {


int value = 0;
boolean bRunning = false;


Button btnStart = null;
Button btnGet = null;
TextView txtView = null;


Thread thread = null;


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


btnStart = (Button)findViewById(R.id.btnStart);
btnGet = (Button)findViewById(R.id.btnGet);

txtView = (TextView)findViewById(R.id.txtValue);


btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
thread = new BackgroundThread();
thread.start();
}
});


btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txtView.setText(Integer.toString(value));
}
});
}


protected void onResume() {
super.onResume();


bRunning = true;
}


protected void onPause() {
super.onPause();


bRunning = false;
value = 0;
}


class BackgroundThread extends Thread {
public void run() {
while (bRunning) {
try {
Thread.sleep(1000);
value++;
} catch (InterruptedException e) {
Log.e("MyJavaThread", "Exception in thread.", e);
}
}
}
}
}