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.

publicclassClockActivityextendsActivity {

    privateSimpleDateFormatsdf=newSimpleDateFormat("hh:mm:ss");

    private TextView mClock;
    privateboolean mActive;
    privatefinal Handler mHandler;

    privatefinalRunnablemRunnable=newRunnable() {
        publicvoidrun() {
            if (mActive) {
                if (mClock != null) {
                    mClock.setText(getTime());
                }
                mHandler.postDelayed(mRunnable, 1000);
            }
        }
    };

    publicClockActivity() {
        mHandler = newHandler();
    }

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mClock = (TextView) findViewById(R.id.clock_textview);
        startClock();
    }

    private String getTime() {
        return sdf.format(newDate(System.currentTimeMillis()));
    }

    privatevoidstartClock() {
        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"