Handler를 이용해서 특정 시간 후에 특정 작업을 실행시키기


특정 시간 후에 특정한 작업이 실행되도록 하는 방법으로 AlarmManager를 이용할수 있지만 간단하게 처리할수 있는 방법으로는 Handler를 이용하면 더 쉽게 처리할수가 있다.

대표적으로 ProgressDialog를 특정 시간 경과 후 종료 시키는 방법을 구현한다면 아래와 같이 간단히 처리할수 있다.

아래 코드는 7초 후에 ProgressDialog를 중지시키는 코드이다.

실행하기 원하는 작업(코드)를 Runnable 인터페이스의 추상 메소드인 public void run() 안에 두면 run안의 코드가 특정 시간 경과후(여기서는 7초) 실행이 된다.

즉 ProgressDialog의 객체인 pDialog를 show() 한 후에 


      ProgressDialog pDialog = new ProgressDialog(this, 

                                                              AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

      pDialog.setCancelable(false);

      pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

      pDialog.setMessage("주변의 BLE 장치를 검색 중입니다.");

      pDialog.show();


      mHandler.postDelayed(new Runnable() {

          @Override

          public void run() {

              pDialog.dismiss();

          }

      }, 7000);



Handler 클래스의 해당 메소드를 보면 다음과 같이 되어 있다.


public final boolean postDelayed (Runnable r, long delayMillis)

⇒ Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached.


r : The Runnable that will be executed.

delayMillis : The delay (in milliseconds) until the Runnable will be executed.


Runnable 객체를 message queue에 추가한 후에 delayMillis 시간 경과 후에 Runnalbe 객체 r을 실행시킨다. 이렇게 처리하면 Thread로는 처리 불가능한 UI 관련 작업도 처리할수 있다.


r : 실행할 코드를 담고 있는 Runnable 객체. Runnable의 추상 메소드 public void run()안에 있는 코드를 실행한다.

delayMillis : 여기에 설정된 시간만큼 경과 후에 r을 실행한다.




+ Recent posts