Search code examples
androidmultithreadingrunnableandroid-handlerui-thread

Android immediately run on ui thread


I have read a lot of other answers on StackOverflow, cant seem to find my answer.

I have a listener in my class, i perform a long running task in an async block:

AsyncTask.execute(() -> {
   // long running task here
   // ...
   listener.updateTitle(newTitle);
});

Once I have the data I pass it back to the relevant class:

 @Override
 public void updateTitle(String newTitle) {
   getActivity().runOnUiThread(() -> title.setText(newTitle));
 }

Now from what I researched online calling runOnUiThread(..) adds the runnable to a queue of tasks that need to be run on ui. My problem is this updating the title is more important than any of the other ui tasks running.

Is it possible to add this task to the front of the queue, or execute currently executing task, then execute this new task and continue executing the tasks as they were in the previous order?


Solution

  • Sure:

    new Handler(Looper.getMainLooper()).postAtFrontOfQueue(() -> title.setText(newTitle));
    

    It may not be sufficient for your needs though as this action will be executed with some delay anyway. If you need to update the title for the next frame, you may want to consider subclassing TextView and providing a synchronized method for setting text from any thread.