Search code examples
javaandroidmultithreadinghandlerrunnable

Creating Runnable class with method that using callback post execution to UI main thread


I have a question whether this code is correct. I have doubts whether background execution in Runnable class executes in run() method or also in constructor... Seems obvious that it is in run() but I would like to ensure my thoughts...

class Tracer implements Runnable {
  private Handler handler;
  private OnTracerCompletedListener callback;  

  Tracer(OnTracerCompletedListener callback) { 
       this.callback = callback;
       handler = new Handler(); // <--- is this on main UI thread?
  }

  @Override
  public void run() { 
      // do something on background thread 
      // after task completed notify invoker of Tracer using callback
      handler.post(new Runnable() { 
           @Override 
           public void run() { 
               if(callback != null) callback.onTracedCompleted(); 
           }
      }
  }

}

Solution

  • The difference between the code in the constructor and the initializer, and the one in the method run is when and from what thread the code will be called.

    So the code in the constructor of Tracer will be called immediately when the instance is created. It will be run in the thread of the caller. The method run will be run in the background (this I just assume since I don't know the architecture of your application).

    So everything what should be done in the background should be done in the method run.