Reputation: 9044
Guess that I have a TextView that I want to update it in some situations. I want to have a thread that every one or two seconds checks the circumstances and updates TextView's text if necessary. Any Idea?
Upvotes: 0
Views: 4658
Reputation: 49976
You can use Handler, in your GUI:
Handler hnd = new Handler() {
public void handleMessage(Message msg) {
if ( msg.what == 101 ) {
//update textview
}
}
}
pass hnd to your thread, and in your thread do:
Message m = new Message();
m.what = 101;
hnd.sendMessage(m);
this assumes that in your separate thread you are doing some work that needs reporting to GUI thread, you can also send text messages
Upvotes: 3
Reputation: 34345
I do something like this:
public class MyClass {
private Handler hUpdate;
private Runnable rUpdate;
public MyClass() { // Constructor
hUpdate = new Handler();
rUpdate = new Runnable() {
// Do your GUI updates here
};
Thread tUpdate = new Thread() {
public void run() {
while(true) {
hUpdate.post(rUpdate);
sleep(500);
}
}
}
tUpdate.start();
}
}
Upvotes: 4
Reputation: 157447
you have to use an handler to update view from another thread. With postDelayed you can set a delay. see the doc:
Upvotes: 1