I am new to Android. Can anyone tell me how to execute a message every 5 seconds. I have tried this code, but it's not showing anything on my emulator. What should I be doing instead?
while(true) {
Toast.makeText(this, "hi", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You should not call Thread.sleep() from the GUI thread. Never do this. Use a handler for such thing.
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
doStuff();
/*
* Now register it for running next time
*/
handler.postDelayed(this, 1000);
}
};
I prefer this way to using timers because the Timer class introduces a new thread and it is now fair to do this.
Is that the sum of your code? What are you setting your activity view to? Android implements an alarm/scheduling service which will be much more friendly to battery life than trying to implement your own.