본문 바로가기

Android/Handler with CountDownTimer

Handler with CountDownTimer

CountDownTimer의 cancel()메소드가 작동하지 않아서 타이머를 취소할 수 없는 문제를 고민하다가 Handler를 경유하여 원하는 작업을 마칠 수 있었다. 반드시 Handler를 사용해야만 하는 일은 아니고 다른 메소드를 선언하고 그 안에서 handlerMessage()와 같은 작업을 하면 된다.

package com.dearpeople.android.test.longtab;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;

public class LongTabActivity extends Activity {
   
 Handler handler;
 boolean handlerStatus;
 TextView textView;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) this.findViewById(R.id.textView);
    // 아래에서 반드시 Handler를 사용해야 하는 것은 아니다. 다른 메소드를 선언하고 호출해도 된다.
        handler = new Handler(){
         public void handleMessage(android.os.Message msg) {
          if(!handlerStatus) return;
          textView.setText("3초경과");
         };
        };
    }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  int action = event.getAction();
 
  TabCount timer = new TabCount(3000, 3000);
 
  if(action==MotionEvent.ACTION_MOVE){
   
  }else if(action==MotionEvent.ACTION_DOWN){
   timer.start();
   handlerStatus = true;
  }else if(action==MotionEvent.ACTION_UP){
   handlerStatus = false;
  }
  return super.onTouchEvent(event);
 }
   
 /*내부클래스로 선언한 타이머 */
 class TabCount extends CountDownTimer {

  public TabCount(long millisInFuture, long countDownInterval) {
   super(millisInFuture, countDownInterval);
  }

  @Override
  public void onFinish() {
   handler.sendEmptyMessage(0);
  }

  @Override
  public void onTick(long arg0) {
  }

 }// 내부클래스 끝
}


 

CountDownTimer timer = new CountDownTimer(1000, 100) 
 {
      @Override
       public void onTick(long l) 
       {
 
       }
 
       @Override
       public void onFinish() 
       {
 
       };
 }.start();

Are we actually starting a new thread that handles ticks ? or what is really happening behind ?
CountDownTimer's implementation uses Handler and sendMessageDelayed(), so no background thread is needed.
This does mean that the timer will not update if you are tying up the main application thread elsewhere in your code.