How do we use runOnUiThread in Android?
Below is corrected Snippet of runThread
Function.
private void runThread() {
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
How runOnUiThread is working in the following code without effecting the existing UI Thread
There are two types of thread in Android.
1 is UI or Main thread on which your UI elements (layouts) are rendered.
2 is Worker Thread in which long task should be executed (like AsyncTask & Networking).
If you write some task in new Thread
, that mean that task will be executed in worker thread.
Now you will use runOnUiThread
or new Handler(Looper.getMainLooper())
because you can not touch UI elements in worker thread.
So basically when you are updating UI like setText()
, or Toast
or any UI operations, you will have to UI thread and you should use worker thread when you are doing some long executions.
Edit
Generally we don't have to manage threading in Android. Because all libraries we use are smart. Although in some cases we have to manage threading as well.
Example
Assume you are calling an web-service(api) in a new Thread
, now when response comes you want show a Toast
. If you just write Toast.show...
directly in response inside worker Thread
you will get exception.
Only the original thread that created a view hierarchy can touch its views.
Now to overcome this issue you have to use runOnUiThread
, so that you can show Toast
.
When may we need to use runOnUiThread in android application?
You have to use runOnUiThread()
when you want to update your UI from a Non-UI Thread. For eg- If you want to update your UI from a background Thread. You can also use Handler
for the same thing.
From the Docs -
Runs the specified action on the UI thread. If the current thread is
the UI thread, then the action is executed immediately. If the current
thread is not the UI thread, the action is posted to the event queue
of the UI thread.
Syntax -
Activity_Name.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// your stuff to update the UI
}
});
Update -
AsyncTask -
If you want to do some
Network operation
or anything that blocks
your UI in that case AsyncTask is best options. There are several
other ways for performing the same Background Operations as you can
useService
,IntentService
also for doing Background Operations.
Using AsyncTask will help you doing your UI work and also won't block
your UI until your background Operation is going on.
From the Docs -
AsyncTask enables proper and easy use of the UI thread. This class
allows to perform background operations and publish results on the UI
thread without having to manipulate threads and/or handlers.
Difference between android runOnUiThread and simple code in java
Assuming that you meant simple code for UIThread code,
What is a thread ?
A thread defines a process running
First runOnUiThread ..
Runs the specified action on the UI thread. If the current thread is
the UI thread, then the action is executed immediately. If the current
thread is not the UI thread, the action is posted to the event queue
of the UI thread.
What is UIThread
- Main thread of execution for your application
Most of your application code will run here
onCreate
,onPause
,onDestroy
,onClick
, etc.So simply Anything that causes the UI to be updated or changed HAS to happen on the UI thread
When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread.Now what if you want to do something that changes the UI?
Then you are welcome to runOnUiThread
You have to use runOnUiThread()
when you want to update your UI from a Non-UI Thread. For eg- If you want to update your UI from a background Thread. You can also use Handler
for the same thing.
Android basics: running code in the UI thread
None of those are precisely the same, though they will all have the same net effect.
The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one (runOnUiThread()
) will execute the Runnable
immediately. The second one (post()
) always puts the Runnable
at the end of the event queue, even if you are already on the main application thread.
The third one, assuming you create and execute an instance of BackgroundTask
, will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground()
, before eventually doing what amounts to a post()
. This is by far the least efficient of the three. Use AsyncTask
if you actually have work to do in a background thread, not just for the use of onPostExecute()
.
Why does runOnUiThread() not work inside Service?
So there's no need to do that, unless you're creating a Thread inside
of it
Gabe Sechan's answer is correct.
But if you are using a separate thread then instead of following code:
new MainActivity().runOnUiThread(new Runnable() {
public void run() {
OverviewFragment.refresh(getApplicationContext());
System.out.println("yay");
}
});
Try, this code:
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
OverviewFragment.refresh(getApplicationContext());
System.out.println("yay");
}
});
As per Android docs
Caution: A service runs in the main thread of its hosting process—the
service does not create its own thread and does not run in a separate
process (unless you specify otherwise).
Android how to runOnUiThread in other class?
Here's a solution if you don't want to pass the context:
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
// code goes here
}
});
Related Topics
Launch Custom Android Application from Android Browser
How to Copy Files from 'Assets' Folder to Sdcard
How to Detect When an Android App Goes to the Background and Come Back to the Foreground
How to Obtain Crash-Data from My Android Application
Can the Android Drawable Directory Contain Subdirectories
Get Visible Items in Recyclerview
Open Facebook Page from Android App
How to Change the Font on the Textview
Android - How to Override the "Back" Button So It Doesn't Finish() My Activity
Checking If an Android Application Is Running in the Background
Difference Between Gravity and Layout_Gravity in Android
Error in Launching Avd With Amd Processor
Saving and Reading Bitmaps/Images from Internal Memory in Android
Repeat a Task With a Time Delay
How to Send a "Multipart/Form-Data" Post in Android With Volley
Your Content Must Have a Listview Whose Id Attribute Is 'Android.R.Id.List'