안드로이드 Timer 사용1 (Timer, timerTask)
목표.
timer를 이용하여 progressBar를 줄어들게 하기.
소스
ProgressBar prog= null;
Timer timer = null;
TimerTask timerTask = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
prog= (ProgressBar)findViewById(R.id.progressBar1);
initProg();
startTimerThread();//타이머 시작
}
//프로그래스bar를 초기화하는 함수
public void initProg(){
prog.setMax(6);//최대값 6 지정
prog.setProgress(6); //현재값 6 지정
}
public void startTimerThread(){
timerTask = new TimerTask(){ //timerTask는 timer가 일할 내용을 기록하는 객체
@Override
public void run() {
// TODO Auto-generated method stub
//이곳에 timer가 동작할 task를 작성
decreaseBar(); //timer가 동작할 내용을 갖는 함수 호출
}
};
timer= new Timer(); //timer생성
timer.schedule(timerTask, 0,1000); //timerTask라는 일을 갖는 timer를 0초딜레이로 1000ms마다 실행
}
public void decreaseBar(){
runOnUiThread( //progressBar는 ui에 해당하므로 runOnUiThread로 컨트롤해야한다
new Runnable() { //thread구동과 마찬가지로 Runnable을 써주고
@Override
public void run() { //run을 해준다. 그러나 일반 thread처럼 .start()를 해줄 필요는 없다
// TODO Auto-generated method stub
int currprog=prog.getProgress();
if(currprog>0){
currprog=currprog-1;
}else if(currprog==0){
currprog=6;
}
prog.setProgress(currprog);
}
}
);
}
위의 소스는... 주석을 다 달아놨으므로 보면 된다.
Timer는 Timer와 TimerTask로 이루어진다.
TimerTask에 run()을 오버라이딩하는데 이 안에 들어가는 내용이 timer가 수행되면 실행 될 내용이다.
Public Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Cancels the TimerTask and removes it from the Timer 's queue. | |||||||||||
The task to run should be specified in the implementation of the run() method. | |||||||||||
Returns the scheduled execution time. |
그 후 Timer.schedule로 timer의 속성을 정해주면 된다.
Schedule a task for repeated fixed-delay execution after a specific delay. |
우리가 사용할 timer의 매서드는 schedule이다.
첫번째인자로는 위에서 할 일을 정해준 timerTask가 첫번째 인자이고, 두번째는 딜레이, 세번째는 몇초마다 timer가 수행될지 정해준다.
수행은 위의 동영상과 같다. 0초가되면 다시 initProg()를 불르면서 progressbar를 초기화한다. 물론 이때는 timer가 초기화가 된 것이 아니라 단순히 프로그래스만 뺑뺑 반복되게 만든것이다.
그렇다면 다음번에는 완전히 timer를 죽이는 방법으로 소스를 짜볼것이다....
아오 피곤해서정신이없네..