Android Handler-Looper implementation

  • I have an Activity with Handler (UI thread)
  • I start a new topic and create handler.post (new MyRunnable ()) - (new workflow)

The Android documentation says about the post method: "Causes Runnable r to be added to the message queue. Runnable will be launched on the thread this handler is bound to."

The handler is bound to the user interface thread. How can an android run runnable on the same user interface thread without creating a new thread?

Will a new thread be created using Runnable from handler.post ()? Or will the run () method be called from the Runnable subclass?

+3
source share
2 answers

The handler is bound to the user interface thread.

Right.

How can an android run runnable on the same user interface thread without creating a new thread?

Any thread, including the main application thread ("UI"), can call post () on the Handler (or on any View , for that matter).

+3
source

Here is an example of crude pseudo-encoded code on how to use handlers - I hope this helps :)

 class MyActivity extends Activity { private Handler mHandler = new Handler(); private Runnable updateUI = new Runnable() { public void run() { //Do UI changes (or anything that requires UI thread) here } }; Button doSomeWorkButton = findSomeView(); public void onCreate() { doSomeWorkButton.addClickListener(new ClickListener() { //Someone just clicked the work button! //This is too much work for the UI thread, so we'll start a new thread. Thread doSomeWork = new Thread( new Runnable() { public void run() { //Work goes here. Werk, werk. //... //... //Job done! Time to update UI...but I'm not the UI thread! :( //So, let alert the UI thread: mHandler.post(updateUI); //UI thread will eventually call the run() method of the "updateUI" object. } }); doSomeWork.start(); }); } } 
+4
source

Source: https://habr.com/ru/post/898988/


All Articles