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);
}
});
}
});
dtThrea开发者_高级运维d.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.
public class ClockActivity extends Activity {
private SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
private TextView mClock;
private boolean mActive;
private final Handler mHandler;
private final Runnable mRunnable = new Runnable() {
public void run() {
if (mActive) {
if (mClock != null) {
mClock.setText(getTime());
}
mHandler.postDelayed(mRunnable, 1000);
}
}
};
public ClockActivity() {
mHandler = new Handler();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mClock = (TextView) findViewById(R.id.clock_textview);
startClock();
}
private String getTime() {
return sdf.format(new Date(System.currentTimeMillis()));
}
private void startClock() {
mActive = true;
mHandler.post(mRunnable);
}
}
You can probably use a handler to post updates to the UI Thread. check out this best practices for updating a timer
http://developer.android.com/resources/articles/timed-ui-updates.html
Instead of designing your own timer to handle this I recommend using a broadcast reciever listing for this intent broadcastet sent every minut: http://developer.android.com/reference/android/content/Intent.html#ACTION_TIME_TICK
If you would like example code for how to do this please let me know.
精彩评论