I've looked at the code here as well as the code here but I still can't seem to get my code to work right. With the 2nd link, I can get a "timer" that counts up on the page, but with the first, my UI locks up. What I'm trying to do is have a seperate thread that continually flips the text in a textswitcher every 3 seconds as long as the app is open. I need it to switch between two values, and have tried something like the following:
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
while(true){
try {
mHandler.post(new Runnable(){
@Override
public void run() {
try {
mSwitcher.setText("ON");
Thread.sleep(1000);
mSwitcher.setText("OFF");
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
}catch (Exception e) {
//tv1.setText(e.toString());
}
}
}
};
Where it will flip "on" or "off" every 2 seconds. I also need to be able to update the text switcher content from the main UI, but haven't gotten to the point i can try and test that. In addition to the above, I have also tried to use an Async Task:
new AsyncTask<Void, Double, Void>() {
@Override
protected Void doInBackground(Void... params) {
while (true) {
mSwitcher.setText("ON");
SystemClock.sleep(2000);
mSwitcher.setText("OFF");
SystemClock.sleep(2000);
}
}
}.execute();
but this did not work either.
An alternative easier method of achieving this is to use a
viewFlipper
rather than aviewSwitcher
. This allows you to do everything that you want using the XML layout alone:To make it look slightly prettier, you can also define the animations to be used in the
viewFlipper
:AdapterViewFlipper Documentation.
try using timer:
Reference for runOnUiThread. You cannot update gui elements from non-ui threads, so trying to update it from
doInBackground()
method ofAsyncTask
will lead to error.I change the UI, use the handler. Make the handler variable private to the Activity and call handler.sendEmptyMessage().
You can use thread or Async task to call the Handler.sendEmptyMessage(ON/OFF).
One more way is to use Handler.sendEmptyMessageDelayed ( ) . By this handler invokes itself after every time the user has set in delayed value.