I come across both runOnUiThread and Handlers, but to me its still seems to be a doubt as on which facts do they differ exactly.
What would be the best way to update UI? Should I use runOnUiThread or Handler?
Already gone through link. Still not able to justify the difference.
Thank you in Advance
runOnUiThread is a method that uses main ui handler so basically they are the same. The only difference is that if you call it inside the ui handler, you just run it instead of post it.
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
Handlers are a nice way to implement an event queue. It doesn't have to run on the main thread, you can set your own looper. RunOnUiThread is basically a shortcut so you dont actually have the initiate a handler and so on.
Handler register itself in which it is declared. or you can set the looper manually also.
Handler is particular useful if you have want to post multiple times data to the main thread.
runOnUiThread is method of Activity. so when you need to update the UI Thread, you must write the code in the following way.
runOnUiThread(new Runnable() {
#Override
public void run() {
// update the ui
}
});
So there is no re-usability.
for example you want to update the status of the file downloading. you should write the above method multiple times.
But using Handler objects update the UI multiple times using same Handler Object.
Related
I'm trying to create a thread that keeps updating a TextView while the Main activity is running
I have used the Runnable class but it doesn't work
Every time my app crashes ...
Is there any way to do that ??
Please help
You may need this in your activity:
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText("something.");
}
});
or this:
textView.post(new Runnable() {
#Override
public void run() {
textView.setText("something.");
}
});
Both of these can let you change UI in work thread.
If you want to keep updating the UI regularly from a runnable, you could start an AsyncTask and update the TextView from postExecute function. postExecute always runs on the UI thread.
You can find more information here:
https://developer.android.com/reference/android/os/AsyncTask.html
Android doesn't allow you to change the UI from another thread. This is a OS design decision, meant to simplify UI handling. You can do whatever you want on secondary threads, but if you want to interact with views and widgets, you have to do it through the UI thread, as explained in the official documentation here.
I will come out straight that this is a assignment question .So I am not looking for a answer but a better answer .
We have a Async Task which takes in three parameters . The progress parameter(i.e 2nd parameter is) is a Runnable .
#Override
public void onProgressUpdate(Runnable ...runnableCommands) {
// TODO -- you fill in here with the appropriate call to
// the runnableCommands that will cause the progress
// update to be displayed in the UI thread.
}
I am able to make calls to this method using publishProgress() in doInBackGround() method.
The challenge is to have this runnable attached to UI Thread. I know that onProgressUpdate() has access to UI thread and we can create a handler to add to message queue . But apparently it is excessive.
Can some guide me to a better way to do this than create a handler
If you have a reference an Activity, an easy way is using the runOnUiThread(Runnable runnable) method. Looking at the source code, it's really easy to see why:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
If you have a reference only to a View, you can use the post(Runnable runnable) method.
The JavaDoc for both states the Runnable will be executed on the main thread.
According to the documentation
onProgressUpdate
This method can be invoked from doInBackground(Params...) to publish updates on the UI thread while the background computation is still running.
You can find a link here AsyncTask
Basically this method already runs on the UI thread. So you dont need any further code (via handelrs or runOnUiThread()).
In your case, you can just directly call run of that Runnable.
How do I use a thread to run some code continuously whilst an Apps running, using the information it gives to periodically update the UI of the App.
Specifically the thread would run some code that searches through a text file in order to find co-ordinates which would then be plotted over a PNG on the UI. This would update automatically say every second maybe every half second, and would clear the image then redraw the points.
How do i first of all set up the thread then second of all send information from the thread back to the UI and have it update?
Any example code would be great or any information you've come across that gives example code. I'm not trying to do it the best way at the moment, just trying to hack it together, so if you know easy and quick (but awful) ways of doing this don't feel afraid to share.
This may help u...
//on create
Thread currentThread = new Thread(this);
currentThread.start();
after on create
public void run() {
try {
Thread.sleep(4000);
threadHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
//don't forget to deal with the Exception !!!!!
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Intent in = new Intent(getApplicationContext(),****.class);
startActivity(in);
}
};
This is a very common scenario and its far boyend the scope of a simple answer to your question.
Here are two usefull links:
http://developer.android.com/guide/components/processes-and-threads.html
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
And there are a lot more.
Here are two different approaches for you as starting point:
Update gui from your thread, only needs syncronzation with the UI thread. Pass your Activity into your thread, it provides the method: runOnUiThread
Define an interface to provide callbacks, let the calling ui class (activity) implement your interface and register it as listener to your thread. Then you can call the callback, when ever you want. Don't for to syncronize
Try to use service(or IntentService - http://developer.android.com/guide/components/services.html) for background work and BroadcastReceiver to update the UI thread from the service.
Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).
Is the sub thread can operate UI? Or it can only use handler to operate in main thread. But I use this code. It did not launch the error. Is anyone has ideas?
new Thread(new Runnable() {
public void run() {
TextView tv=(TextView) findViewById(R.id.aaa);
tv.setText("111");
}
}).start();
No, you cannot perform UI operation from a different thread. If you want to update the UI, you must use handlers. Alternatively you can also use async tasks or Activity.runOnUiThread.
Generally only the main thread should touch the UI. You are not promised to get an exception otherwise, but you are very likely to.
You should use handler / asyncTask / runOnUiThread as they are the ways to modify UI, other ways may work in some cases, but are not guaranteed.
In my Android app, I am extracting the code to update UI elements into a separate utility package for reuse. I would like my code to be proactive and update the UI differently if the current execution context is from a UI thread versus a non-UI thread.
Is it possible to programmatically determine whether the current execution is happening on the UI thread or not?
A trivial example of what I am looking to achieve is this - my app updates a lot of TextViews all the time. So, I would like to have a static utility like this:
public static void setTextOnTextView(TextView tv, CharSequence text){
tv.setText(text);
}
This obviously won't work if called from a non-UI thread. In that case I would like to force the client code to pass in a Handler as well, and post the UI operation to the handler.
Why don't you use the runOnUiThread method in Activity
It takes a runnable and either runs it straight away (if called from the UI thread), or will post it to the event queue of the UI thread.
That way you don't have to worry about if your method has been called from the UI thread or not.
When you're not sure the code is executed on the UI thread, you should do:
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// your code here
}
});
This way, whether you're on the UI thread or not, it will be executed there.
You can use the View post method.
Your code would be:
tv.post(new Runnable() {
public void run() {
tv.setText(text);
}
});