In the previous article, we implemented time display, but it was static and could not be changed dynamically. How can we make the static time dynamically change in seconds?
In the previous article, we obtained the time by using the Calendar () Class getTime () method, which only returns the time at which a program starts, to dynamically display the time in seconds, we can consider using multiple threads to refresh the main interface every second, in this way, the time of the current time point can be obtained every second to display the time.
In Android, we can use Handler to implement multithreading.
Handler is responsible for sending and processing messages in Android. Its main purposes include:
(1). Send a message as planned or execute a Runnable (using the post method );
(2). Put messages sent from other threads into the message queue to avoid thread conflicts (often used to update the UI)
We mainly use two Handler Methods: post (Runnable) and postDelayed (Runnable, long)
The Code is as follows:
Public class DateAndTime extends Activity {
/** Called when the activity is first created .*/
Private String DEFAULT_TIME_FORMAT = "yyyy-MM-dd hh: mm: ss ";
Private TextView textview01;
Private String time;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Handler. post (updateThread );
// Add the thread object to be executed to the thread queue. The thread object will be added to the thread queue of the handler object.
Textview01 = (TextView) findViewById (R. id. textview01 );
}
// Create a Handler object
Handler handler = new Handler ();
// Create a thread object
Runnable updateThread = new Runnable (){
// Write the operation to be executed in the run method of the thread object
Public void run (){
Handler. postDelayed (updateThread, 1000 );
// Call the postDelayed () method of Handler
// The function of this method is to put the thread object to be executed into the queue and run the specified thread object after the end of time.
// The first parameter is of the Runnable type: the thread object to be executed.
// The second parameter is of the long TYPE: Delay Time, in milliseconds
SimpleDateFormat dateFormatter = new SimpleDateFormat (DEFAULT_TIME_FORMAT );
Time = dateFormatter. format (Calendar. getInstance (). getTime ());
Textview01.setText (time );
}
};
}
Run the following commands in the simulator:
From the tianshuguang Column