본문 바로가기
안드로이드 자바

[Java][Android] Timer 클래스 활용해 카운트 작업 하기

by teamnova 2025. 4. 8.
728x90

안녕하세요

오늘은 Timer 클래스를 활용해 카운트 작업을 해보도록 하겠습니다.

Timer 클래스는 반복적인 작업을 할 때 유용하게 활용이 가능합니다.

 

전체 코드입니다.

 

MainActivity.java

public class MainActivity extends AppCompatActivity {

  private TextView textTimer;
  private Button btnStart;
  private Timer timer;
  private int tickCount = 0;
  private Handler handler = new Handler(); // UI 갱신용

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

    textTimer = findViewById(R.id.textTimer);
    btnStart = findViewById(R.id.btnStart);

    btnStart.setOnClickListener(v -> startTimer());
  }

  private void startTimer() {
    tickCount = 0;
    if (timer != null) {
      timer.cancel();
    }

    timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        tickCount++;
        handler.post(() -> textTimer.setText("카운트 " + tickCount));
      }
    }, 0, 2000); // 처음엔 즉시 실행, 이후 2초마다 반복
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (timer != null) {
      timer.cancel(); // 액티비티 종료 시 타이머 정리
    }
  }

 

activity_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"
  android:gravity="center"
  android:padding="16dp">

  <TextView
    android:id="@+id/textTimer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="타이머 시작 전"
    android:textSize="24sp" />

  <Button
    android:id="@+id/btnStart"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="타이머 시작"
    android:layout_marginTop="20dp"/>
</LinearLayout>

 

 

저는 타이머를 2초로 설정해놓고, 매 2초마다 카운트를 하도록 설정했습니다.

 

이를 활용해 다양한 반복작업을 쉽게 구현할 수 있습니다.

 

시연 영상입니다.