This simple application displays the date and time using a TextView. The TextView must be updated with the correct time periodically so a Handler is used to schedule updates. This is accomplished by creating a Runnable class in which the public void run() method obtains the current time and updates the TextView. Handlers can schedule a Runnable to be executed after a delay, by rescheduling the same Runnable from within the run() method the time will be updated periodically.
First we will take a look through the project to see what is happening, click here to download the source.
Open the Time.java file located in the src/ directory in edu.calpoly.android package
Take a look at the public void onCreate(Bundle savedInstanceState) method, this method is called when an Activity is first started and is used for initializing the Activity
Notice how the TextView is initialized and the setup for periodic time updates is completed
UpdateTimeTask is an inner class that contains the run() method used to update the time
The Date class is used to format the date and time into an easy to read string, which is then passed into the TextView
The last call in the run() method adds another call to the UpdateTimeTask to be executed after a 100ms delay
Run this application on an emulator or device to see what it looks like
To modify the application you will be adding another TextView that displays a timer that displays the number of seconds since the application was started.
First you will need to add another TextView element to the layout file, res/layout/main.xml, this needs to be placed just below the first TextView within the LinearLayout element, give this TextView an id so it can be accessed from Time.java
In Time.java, add a new member variable for the timer TextView and initialize it, similar to the other TextView
To update the timer TextView the same UpdateTimeTask can be used, here are a few hints on calculating the number of seconds that have passed:
System.getCurrentTimeMillis() returns a long value that represents the current time
You can obtain the start time of the program by using the above call in the onCreate method
When finished you should be able to run the application and see something like this: