Android Java runOnUiThread ()

I messed up the runOnUiThread method a bit. And if I just make a method in my activity:

public void Test() { runOnUiThread(new Runnable() { public void run() { Log.v("mainActivity", "test"); } }); } 

I noticed that this runnable only works once. However, this is not a problem. I was wondering if I completely missed something, and he did something in the background, which would lead to a decrease in the frame rate when I performed this method a couple of times.

+4
source share
2 answers

This is the full body from Activity.runOnUiThread (Runnable) :

 public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } } 

The body of the method is still running in the background thread, and the mHandler of the android.os.Handler class implements an internal queue for Runnables sent to it, so if you aren’t "Performing blocking work in Runnable (which is a big no-no in the user interface thread) or calls this method more than a thousand times in a short period, you will not see any difference.

Now, if you called Handler.postAtFrontOfQueue (Runnable) , then there would be a problem, because your Runnable is essentially a "slice". In this case, it can cause a stutter because your Runnable is being executed instead of any user interface updates that should have been performed (e.g. scrolling).

Please note that you only need to run UI updates in the UI thread, for example, call any methods in the view (thus the name "UI thread" and why this method exists) or any operation that is explicitly stated in the documentation that it should be executed in the user interface thread. Otherwise, if you are already in the background thread, there is no real reason to leave it.

+12
source

It is unlikely that this will lead to a significant interruption of your user interface, but in fact it makes no sense to run it in the user interface thread.

If you are doing a significant amount of work, you must make sure that you are not doing this in the user interface thread.

+1
source

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


All Articles