Search code examples
androidperformanceandroid-handler

Android: Stop a handler at a certain time in an Intent Service


I have an intentService that starts a handler, but after a certain amount of time I need to stop the handler. I'm not sure how to do this. I have the class below, but I'm just not sure how to stop the handler once the time is reached, or when a certain amount of hours/min passes. I would like this to be as efficient as possible please.

public class RedirectService extends IntentService {

   private Handler handler;
   private Runnable runnable = new Runnable() {
       @Override
       public void run() {
           foobar();
           handler.postDelayed(this, 2000);
       }
   };

   public LockedRedirectService() {
       super("RedirectService");
   }

   @Override
   protected void onHandleIntent(Intent redirectIntent) {
       // Gets data from the incoming Intent
       int hour = redirectIntent.getIntExtra("hour", 0);
       int min = redirectIntent.getIntExtra("minute", 0);



       handler.postDelayed(runnable, 2000);
       handler.removeCallbacks(runnable);
   }
}

Solution

  • Start a new thread and wait. When time's up, stop and remove the runnable. Or use handler to post another delayed runnable to stop and remove the working runnable.

        public class RedirectService extends IntentService {
    
        private Handler handler;
        private boolean mRun = false;
        private Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (mRun) {
                    foobar();
                    handler.postDelayed(this, 2000);
                }
            }
        };
    
        public LockedRedirectService() {
            super("RedirectService");
        }
    
        @Override
        protected void onHandleIntent(Intent redirectIntent) {
            // Gets data from the incoming Intent
            final int hour = redirectIntent.getIntExtra("hour", 0);
            final int min = redirectIntent.getIntExtra("minute", 0);
    
    
            mRun = true;
            handler.postDelayed(runnable, 2000);
            //handler.removeCallbacks(runnable);
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Thread.currentThread();
                    try {
                        Thread.sleep((hour * 60 + min) * 60 * 1000);
                    } catch (Exception ignore) {}
                    mRun = false;
                    handler.removeCallbacks(runnable);
               }
            }).start();
    
            /* or use handler
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mRun = false;
                    handler.removeCallbacks(runnable);
               }
            }, (hour * 60 + min) * 60 * 1000);
            */
        }
    
        }