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(); }
source share