Showing current time in Android and updating it?
Android has a view for this already.
http://developer.android.com/reference/android/widget/TextClock.html
You can use it directly in XML like so
<TextClock
android:id="@+id/textClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
It is min api 17, so you if need to go lower than that just look into
http://developer.android.com/reference/android/widget/DigitalClock.html
Worst case scenario you can subclass textview and steal the code from the textclock source. it should be fairly straightforward
boolean run=true; //set it to false if you want to stop the timer
Handler mHandler = new Handler();
public void timer() {
new Thread(new Runnable() {
@Override
public void run() {
while (run) {
try {
Thread.sleep(20000);
mHandler.post(new Runnable() {
@Override
public void run() {
Calendar c = Calendar.getInstance();
int min = c.get(Calendar.MINUTE);
int hour=c.get(Calendar.HOUR);
TextView.setText(String.valueOf(hour)+":"+String.valueOf(min));
}
});
} catch (Exception e) {
}
}
}
}).start();}
in the onCreate call it like this
timer();
Something like this should do the trick
final Handler someHandler = new Handler(getMainLooper());
someHandler.postDelayed(new Runnable() {
@Override
public void run() {
tvClock.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
someHandler.postDelayed(this, 1000);
}
}, 10);
You should keep a reference to the handler and the runnable to cancel this when the Activity
goes to pause and resume when it resumes. Make sure you remove all callbacks to handler and set it to null
in onDestroy