Search code examples
androidmultithreadinghandlercountdowntimer

CountdownTimer in a separate thread with looper


I am trying to implement a countdown to warn users when they are exiting an area. To do this, I am attempting to use a CountdownTimer in a JobIntentService; however, this means the CountdownTimer is in a thread without a looper causing an exception to be thrown. java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #1,5,main] that has not called Looper.prepare()

I have found this Question on a CountdownTimer in its own thread with looper, but the answer there is 6-7 years old and I want to be using the best practices for threading and handlers.

If anyone could give a little insight into how to do this in a cleaner way, it would definitely be appreciated.


Solution

  • Always create handler with the use of Looper.

    1) Creater UI handler to update the UI

    Handler mainThreadhandler = new Handler(context.getMainLooper());
    mainThreadhandler.post(new Runnable(){
       public void run(){
        // UI work
       }
    });
    

    2) Create Thread handler, to run the background task.

    HandlerThread bgThread = new HandlerThread("MyHandlerThread");
    bgThread.start();
    Handler bgHandler = new Handler(bgThread.getLooper());
    bgHandler.post(new Runnable(){
       public void run(){
        // background work
       }
    });
    

    Don't forget to cleanup while finishing the activity.

    @Override
    public void onDestroy() {
      bgHandler.getLooper().quit();
      super.onDestroy();
    }