Skip to content Skip to sidebar Skip to footer

Updating Time And Date By The Second In Android

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 A

Solution 1:

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);
    }
}

Solution 2:

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


Solution 3:

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.


Post a Comment for "Updating Time And Date By The Second In Android"