Can I use runOnUiThread() inside a thread to update the user interface while running the thread, or handler is more efficient ? .
Yes you can use runOnUiThread() from a non UI thread to update the UI. That method uses a handler internally if you are not currently on the UI thread so using your own handler will not be more efficient. If you are already on the UI thread then the runnable will be executed immediately.
Efficiency isn't a big deal here. Handler might be useful if you need to call another class (for instance, if your thread runs in a class and you need to update the fragment). If you're in a fragment/activity and have access to the elements you need to update, then it may be easier to do runOnUIThread. It's all about code access really.
I personally use callbacks.
Related
I have the following Kotlin code, executed from the UI thread of Android:
Runnable {
doSomeSuff() // Which thread will it run?
}.run()
On which thread will it run? The UI thread?
Your Runnable will be executed on the Thread it was created. In your case - UI thread. The question is - what do you want to achieve? There are bunch of built-in capabilities to perform background related work. I'll provide wider answer - if you explain your requirements.
From Android Documentation:
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. The class must
define a method of no arguments called run.
This interface is designed to provide a common protocol for objects
that wish to execute code while they are active. For example, Runnable
is implemented by class Thread. Being active simply means that a
thread has been started and has not yet been stopped.
Why it is different from Thread:
When an object implementing interface Runnable is used to create a
thread, starting the thread causes the object's run method to be
called in that separately executing thread.
I am a beginner in android application development.I am working with threads in android.I have read about a runOnUiThread which run code on main UI(if i am not wrong?i guess.).
My question is what is the difference between normal code on main UI and code inside runOnIUThread.
Example:1
class A
{
getDataFromServer(foo);//Code on mainUI
}
Example:2
getActivity.runOnUiThread(new Runnable(){
#Override
public void run(){
getDataFromServer(foo);
}
});
What is difference in both example.Please help me.Your response will be a new learning for me.
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.
Normally your code is executed on your UI thread. For longer taking tasks (such as network requests, etc...) you will use a background tasks (Handler, AsyncTask, Thread, ...).
As your Views can only be touched from a UI thread, you use runOnUiThread() if you are executing code in a background thread and you need to update your views, from this background thread.
To explain 'why' Android has the 'runOnUiThread()' option, it is important to understand that java is only used to create the bytecode (dex) that Android uses. The code running on the phone is NOT java.
Additionally, Android threads 'can' have a thing called a 'looper'. This 'looper' is what handles 'tasks(technically runnables and messages)' in order via a queue. The 'main ui thread' has by default a looper already attached to it.
That means that your runnable you created was put onto the looper's queue of the main UI thread. (this is why the runnable is NOT instantaneously ran, but will be ran 'quickly'/'soon')
The reason you'd use a runnable to run code on the UI thread is because you are in some other 'background thread' that you created... and want to update the UI in some way. (Only the UI thread can interact with the UI)
I have a thread which is started in onCreate() and this thread fetches some data.
Is it possible that before the thread is terminated should be able to update the ListView?
Now as the thread is not the UI thread, it cannot directly update the listview array adapter.
Is there a way out?
I was thinking that is it possible to trigger a Handler from thread whose runnable gets executed on main UI thread.
Not sure if I understood your problem completely, but I believe there are two ways to achieve what you want:
1- Start an AsyncTask instead of a thread. AsyncTask's onPostExecute() will run in the UI thread, which means you can do anything UI-related in there. You can start the AsyncTask in onCreate(), and, once it finished, it calls a method on your activity which does:
myAdapter.notifyDataSetChanged();
2- Use runOnUIThread()
Use your Activity's runOnUiThread(Runnable action)
link
According to the documentation one of three options should be used for accessing the UI thread from a different thread.
These are the options:
Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
When should I use which? They all seem to add a Runnable to the message queue of the UI thread.
I assume postDelayed is only really useful if you want to schedule a Runnable for later and they only mentioned it because it also runs the Runnable on the UI thread.
And for extra confusion there is also AsyncTask. When should I use that now?
runOnUiThread and View.post are exactelly the same they both send a runnable object to the activity's Handler . so use whichever you like.
Regarding the AsynchTask it is not used to run on the UI thread. but after an Asynch task finishes working it calls a method called OnPostExcute on the UI thread.
There is a very great tutorial on this subject Here
If you need a mechanism for returning to the UI thread that is available from everywhere without needing a context, you can use this:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(Runnable);
I always choose runOnUiThread, I think so is the best way to run something on the same UI Thread.
AsyncTasks are tricky, it's a good idea but if you want to use something new, use loaders or IntentService.
Forget about AsyncTask, it's not for running code in the UI thread, but running code in a background thread starting the AsyncTask from the UI thread.
Regarding the other options, feel free choosing any of them. If you are dealing with a View object, it is likely you are already on the UI thread. Therefore, you better keep a reference to the Activity context from the other thread and call runOnUiThread.
I will recommend you to use AsyncTasks, they were designed to do hard work in other thead (doInBackground()) and then syncronize with UI thead to push work results (onPostExecute()), and of course you can periodically update UI with work progress (onProgressUpdate()).
If you want to run more than one AsyncTask concurrently on Android Version greater than HONEYCOMB, you can use my small lubrary: Android-AsyncTask-Executor
Can someone explain to me what exactly the UI thread is?
On developer.android.com it says about the runOnUiThread function
public final void runOnUiThread (Runnable action)
Since: API Level 1 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.
Does the UI thread mean that this will be run everytime the activity is pushed the the background by some ui activity like incoming call or screen dimming etc.? If not, what exactly does the UI thread include ?
Thank you
The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components (Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to those components are performed in this thread.
For instance, let's say your application is a single Activity class. Then all of the lifecycle methods and most of your event handling code is run in this UIThread. These are methods like onCreate, onPause, onDestroy, onClick, etc. Additionally, this is where all of the updates to the UI are made. Anything that causes the UI to be updated or changed HAS to happen on the UI thread.
For more info on your application's Processes and Threads click here.
When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread. So what happens if this background thread needs to do something that changes the UI? This is what the runOnUiThread is for. Actually you're supposed to use a Handler (see the link below for more info on this). It provides these background threads the ability to execute code that can modify the UI. They do this by putting the UI-modifying code in a Runnable object and passing it to the runOnUiThread method.
For more info on spawning worker threads and updating the UI from them click here
I personally only use the runOnUiThread method in my Instrumentation Tests. Since the test code does not execute in the UIThread, you need to use this method to run code that modifies the UI. So, I use it to inject click and key events into my application. I can then check the state of the application to make sure the correct things happened.
For more info on testing and running code on the UIThread click here
If you execute blocking code (e.g. a Http-Request) in a separate Thread, consider using AsyncTask. Its doInBackground-Method runs on a separate Thread. AsyncTask provides you with methods onProgressUpdate and onPostExecute which are guaranteed to run on the UI thread.
If you need GUI-progress updates (e.g. via a progressbar) call publishProgress inside doInBackground. This leads to a subsequent call of onPublishProgress which is also guaranteed to run on the UI thread.
onPostExecute is automatically called after doInBackground returns.
All UI drawings etc. happen in a separate thread. Its called the UIThread. If you want to make any change to UI u must use make sure it happens in UIThread's context.
Easiest way of doing it is to make use of runOnUiThread