I have got to know that the Handlers are basically used to Run the Small Section of Code and etc...
But I didn't got the exact scenerio about when particularly It is Ideal to use the Handlers!
Any Help???
Thanks,
david
Handlers are used for updating the UI from other (non-UI) threads.
For example, you can declare a Handler on your Activity class:
Handler h = new Handler();
Then you have some other tasks on different thread that wants to update some UI (progress bar, status message, etc). This will crash:
progressBar.setProgress(50);
Instead, call this:
h.post(new Runnable() {
public void run() {
progressBar.setProgress(50);
}
});
I'm a newbie myself but I'll give a newbie example since I recently learned this, I'm sure there are many more.
You have to use a Handler when you want to update the main UI when you are doing something in another thread. For example in my case I used it in image slideshow code that runs in a TimerTask. You cannot update the main UI ImageView with the next image from within the TimerTask because it's in a different thread. So you have to use a Handler or you get an error.
This is just one example. I hope this helps.
Related
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.
I have two JNI native methods that callback Java methods in my UI.
1) Display progress..
2) Dismiss progress
Both of the above calls are definitely in sequence. They both call Java methods that create new runnables as follows:
m_Activity.runOnUiThread( new Runnable()
{
#Override
public void run()
{
DisplayProgressUpdate( m_ProgressPercent );
}
} );
--
m_Activity.runOnUiThread( new Runnable()
{
#Override
public void run()
{
m_Progress.dismiss();
}
} );
What I am seeing is that the dismiss runnable is happening before the progress update runnable completes. I would have thought that because they were called in sequence and because they are both being requested on the same (UI) thread that they would occur in sequence as well. Is this not the case?
Is this why I should be using something such as a Handler to synchronise/sequence these calls?
EDIT: OK, I implemented a Handler and still observed the same behaviour. It was actually my debug that confused me. It looked as though the Dismiss Java code was happening before the progress update had completed, but what it was in fact was the Java debug printing as soon as JNI called the Java method which did the posting to the handler - not the actual runnable thread itself. So.. tajonn07 was right in a way - the dialog box was closing before I had a chance to see it and my debug lead me astray. Thanks for helping guys.
I suspect that what you're seeing isn't the dismiss being executed first, but instead it's being executed so quickly after the display that it doesn't even show.
I would suggest using a handler. But even with a handler, if it's in your UI thread, it will freeze your screen.
It's a bit messy, but you could drop both those blocks of code inside another thread with a handler. It's not the cleanest solution but it should do the trick!
runOnUiThread is not added on queue in android , this is called immediately when it invoke.
If you want queue / sequence(ie one after another), you have to use Handler.
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).
This feels like it should be a very simple task but I am having a lot of problems with it. In my program I have extended the WebView class for my own and am trying to add it to a layout programatically. Here is my code:
Looper.prepare();
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
MyWebView webView = new MyWebView(context,1,2,3,4);
appState.projectWebView.add(webView);
addView(webView);
}
});
When I run this code it does not execute. I have no idea why. Thanks for you time.
You cannot create a Handler outside of an UI thread. Well, you can, but you will have to turn that thread into a message queue with much more than just Looper.prepare().
What you need to do is pass an Activity to the class that contains the code in your sample, and call runOnUiThread() on it. Alternatively, you can pass a Handler created on a UI thread, for instance create it at the thread that runs your Activity UI, and then call post on that handler.
Note that this is awful advice, you seem to be trying to do things against the Android framework. But, without further information of what you are actually trying to do, there is no much that can be said.
I tried to look clear answer for it but wasn't able to find it anywhere. I am running background thread in main activity that checks for certain variable and if it is true it should show alert dialog. I also want this dialog to show up on any focused activity of the application. I tried it by adding Looper.prepare() and Looper.loop() to the thread but it does not work properly and it affects while() loop that I use to check variable in that thread. Can anyone please help me in finding out what is the best way to implement this?
Thanks.
If you construct the background thread using the main/ui thread, you can create a Handler in the constructor. When you want to run some code on the main/ui thread, you simply Handler.post(Runnable r) with a runnable to the ui thread.
If your background thread is not being constructed on the ui/main thread, you can use a BroadcastIntent to and a BroadcastReceiver pattern to send messages between your background thread and your foreground activities. This is especially useful if you are switching foreground activities during the useful life of your background thread.
You may want to try creating an implementation of Runnable and passing that to a View's post() method.
final Runnable r = new Runnable() {
public void run() {
//code to display dialog
}
}
final View view = findViewById(R.id.XYZ);
view.post(r);
This will run the Runnable on the UI thread.
Ok, i can see two approaches. The first one is a dirty but quick:
You can extend TimerTask and Handler classes. YourTimerTask will check variable and send a Message to YourHandler. YourHandler should override handleMessage and show a dialog.
The second one might be an overkill, but still. Android is event-based. It means that system gives you an opportunity to create your own events and handle it. So, you can start a Service, which will check your variable and send a Broadcast (can be local). In your activity you have to create your own BroadcastReceiver and register it. This receiver will handle a message.