1. ThreadTest
Thread 를 활용해 다음과 같은 화면 만들어보기
▼결과화면

▼activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
▼MainActivity.java
package kr.ac.dju.threadtest01;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
private Thread thread;
private TextView textView;
private int number = 0;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
thread = new Thread() {
@Override
public void run() {
super.run();
while (true) {
try {
Thread.sleep(1000);
number++;
Log.i("test", "thread running..."+number);
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(String.valueOf(number));
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
thread.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
thread.interrupt(); //액티비티 종료 시 스레드도 정리
}
}'[Android] 안드로이드' 카테고리의 다른 글
| [ 안드로이드 응용 ] 바운스 볼(공 튀기기) 구현하기 (0) | 2026.04.15 |
|---|---|
| [ 안드로이드 기본 ] 터치로 움직이고 중력이 작용하는 CutomView 만들기 (0) | 2026.04.15 |
| [ 안드로이드 기본 ] 간단한 Handler 테스트 (0) | 2026.04.10 |
| [ 안드로이드 기본 ] 간단한 게임화면 구현 _ ScreenChange (1) | 2026.04.10 |
| [ 안드로이드 기본 ] Toast - setOnClickListener() , LogCat - 로그출력 (0) | 2026.04.10 |