[Android/Kotlin] 타이머 중지/재시작 -Timer/TimerTask

SoyoungLee·2022년 10월 24일
0

안드로이드/코틀린

목록 보기
48/68
post-thumbnail

💌 [Android/Kotlin] Timer/TimerTask - 타이머 중지/재시작

📌 Timer 와 TimerTask 를 이용해 카운트다운을 구현해보려 한다.

💜 먼저 타이머 초를 입력할 EditText 와 시작 버튼, 남은 시간을 보여주는 TextView 를 만들어준다.

<LinearLayout
		xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">

        <EditText
            android:id="@+id/et_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="초 입력"
            android:inputType="number"
            android:textAlignment="center" />

        <Button
            android:layout_marginStart="10dp"
            android:id="@+id/btn_timer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="타이머 시작" />

        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:text="남은 초" />

    </LinearLayout>

💜 Timer 와 반복 실행 할 TimerTask 를 생성.

💜 schedule 을 이용해 설정한 time 시간에, 설정한 task 작업을 수행.

btnTimer.setOnClickListener {
	var mSecond: Long = etNumber.text.toString().toLong()
	val mTimer = Timer()
	// 반복적으로 사용할 TimerTask
	mTimerTask = object : TimerTask() {
		override fun run() {
			val mHandler = Handler(Looper.getMainLooper())
			mHandler.postDelayed({
				// 반복실행할 구문
				mSecond--
				Log.d(TAG,"$mSecond")
				if (mSecond <= 0) {
					mTimer.cancel()
					Log.d(TAG,"타이머 종료")
 				}
				binding.tvTime.text = "$mSecond 초"
			}, 0)
		}
	}
	mTimer.schedule(mTimerTask, 0, 1000)
	Log.d(TAG,"${mSecond}초 타이머 시작")
}

💜 10 을 입력 후 타이머 시작


profile
Android Developer..+ iOS 슬쩍 🌱 ✏️끄적끄적,,개인 기록용 👩🏻‍💻

0개의 댓글