Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Dialog
- podinit
- viewmodel
- RestAPI
- PostgreSQL
- DialogFragment
- addTextChangedListner
- 리눅스
- springboot
- android
- livedata
- backgroundTint
- Button
- prolificinteractive/material-calendarview
- cocoapod
- editText
- calendar
Archives
- Today
- Total
코코딩딩
[안드로이드/android] Timer 제한시간 만들기 본문
제한시간을 두어 2분이 경과하면 메세지를 출력하는 기능을 구현하고자 한다.
MainActivity
Timer를 이용해 1초마다 int time의 값을 -1 씩 해 TextView(timeTv)에 출력하는 방법으로 타이머를 구현하였다.
타이머를 실행하는 부분은 timer.schedule(TaskCreate(),1000,1000); 인데 중간의 1000은 앱이 실행하자마자 바로 시간초가 진행되 1초의 딜레이를 준 것이며 마지막 1000이 1초마다 실행되는 부분이다.
안드로이드는 메인쓰레드 에서만 화면을 그릴 수 있기 때문에 runOnUiThread를 통해 textView의 값을 set 할 수 있다.
타이머가 2분이 되기 전에 화면을 이동 하더라도 타이머가 돌고있기 때문에 화면을 벗어날 때 timer.cancel(); 처리를 해주어야 한다. 처리를 하지 않으면 다른 화면에서 토스트메세지가 출력되는 일이 발생할 수 있다.
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.widget.Toast;
import com.example.timertest.databinding.ActivityMainBinding;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
private int time = 0;
private Timer timer = new Timer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
timer.schedule(TaskCreate(),1000,1000);
}
private TimerTask TaskCreate(){
binding.timeTv.setText("02:00");
time = 120;
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(time == 0){
// 시간초가 0초가 되었을 때 원하는 처리 실행
timer.cancel();
Toast.makeText(MainActivity.this, "제한시간 2분을 초과했습니다.", Toast.LENGTH_SHORT).show();
}
time -= 1;
int min = time / 60;
int sec = time % 60;
binding.timeTv.setText(String.format("%02d:%02d",min,sec));
}
});
}
} ;
return timerTask;
}
// 뒤로가기 버튼을 눌렀을 때 timer가 종료되게 설정
// 다른 화면을 이동할 때 cancel();을 통해 타이머를 종료해주어야 한다.
@Override
public void onBackPressed() {
super.onBackPressed();
timer.cancel();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/time_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
'일단기록 > 매일기록' 카테고리의 다른 글
[안드로이드/android] editText 색상 변경(활성화), 텍스트 변경 감지 (0) | 2022.05.17 |
---|---|
[스프링/springboot] restapi 만들기 (mybatis, postgresql) (0) | 2022.05.13 |
[안드로이드/android] color 사용하기 (java,xml) (0) | 2022.05.11 |
[안드로이드/android] 차트 라이브러리 (MPAndroidChart) (0) | 2022.05.10 |
[스프링 / spring] 비밀번호 처리하기 (비밀번호 확인,변경) (0) | 2022.05.04 |