I want to display the time and date in a TextView in real time (updating it by the minute). Currently, I have this. Is this the best way of doing that, considering memory use and Android best practice? (note: DateFormat is java.text.DateFormat)
private Thread dtThread;
public void onCreate(Bundle savedInstanceState) {
...
getDateAndTime();
}
private void getDateAndTime() {
dtThread = new Thread( new Runnable() {
@Override
public void run() {
Log.d(TAG, "D/T thread started");
while (!Thread.currentThread().isInterrupted()) {
try {
update();
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d(TAG, "D/T thread interrupted");
}
}
}
public void update() {
runOnUiThread( new Runnable() {
@Override
public void run() {
Date d = new Date();
String time = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(d);
String date = DateFormat.getDateInstance(DateFormat.LONG).format(d);
TextView timeView = (TextView) findViewById(R.id.textStartTime);
TextView dateView = (TextView) findViewById(R.id.textStartDate);
timeView.setText(time);
dateView.setText(date);
}
});
}
});
dtThread.start();
}
protected void onPause() {
super.onPause();
dtThread.interrupt();
dtThread = null;
}
protected void onResume() {
super.onResume();
getDateAndTime();
}
I would use a Runnable and post it with a delay to a Handler.