Update time and date second in Android

I want to display the time and date in TextView in real time (updating it every minute). I have it now. Is this the best way to do this, given memory usage and best Android practices? (note: DateFormat - 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(); } 
+4
source share
3 answers

I would use Runnable and send it with a delay to the 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); } } 
+5
source

Perhaps you can use a handler to post updates to the user interface thread. check out these timer update guidelines

http://developer.android.com/resources/articles/timed-ui-updates.html

+1
source

Instead of developing your own timer for this, I recommend using a list of broadcast receivers for this intentional broadcast sent every minus: http://developer.android.com/reference/android/content/Intent.html#ACTION_TIME_TICK

If you need some sample code on how to do this, let me know.

+1
source

All Articles