Timer
In some cases, we may need to do some operations regularly. For example, send heartbeat packets at regular intervals, regularly query data to refresh the UI interface, or do some polling tasks. If you have these requirements, then the timer is a good choice.
How to use the timer
Register timer
For ease of use, we add a timer in the form of a filled structure. In the Logic.cc file, there will be such a structure array by default :/** * Register timer * Just add to this array */ static S_ACTIVITY_TIMEER REGISTER_ACTIVITY_TIMER_TAB[] = { //{0, 6000}, //Timer id=0, Period 6second //{1, 1000}, };
If we want to add a timer, we only add a structure to this array. The definition of this structure is as follows:
typedef struct { int id; // Timer ID, can not redefine int time; // Timer period unit/ms }S_ACTIVITY_TIMEER;
Add timer logic code
After registering the timer in the array, when a timer is triggered, the system will call thevoid onUI_Timer(int id)
function in the corresponding Logic.cc file. All operation codes for this timer are Added to this function, the function is specifically defined as follows:/** * Timer trigger function * It is not recommended to write time-consuming operations in this function, otherwise it will affect UI refresh * @param id * The id of the currently triggered timer is the same as the id at registration * @return true * Keep running the current timer * false * Stop running the current timer */ static bool onUI_Timer(int id){ switch (id) { default: break; } return true; }
This function is also generated by default with the Logic.cc file.
Note that the parameter id of the function is the same as the id value defined in the structure array. We can determine which timer is currently triggered based on the id value, so as to make some targeted operations.
[!Note] Note: The timers of each activity are independent, and the id of the timers of different activity can be the same;
The registered timer, as long as the activity is not destroyed (see Activity life Cycle), it will always run;
No need to stop manually after registration, it will stop automatically when the activity is destroyed.
Sample
Next, we will describe the use of timers with a specific example.
Suppose we need to implement such a function: There is an integer variable, every second, the variable is accumulated by 1, and the latest result is displayed on the screen.
The implementation process is as follows:
First, we add a text control to the UI file to display the accumulated result.
Register the timer, add a structure to the timer array of mainLogic.cc, the timer id is 1, and the time interval is 1 second. Note that the time unit is milliseconds.
In timerTestLogic.cc, define a static integer variable and initialize it to 0
In the
void onUI_Timer(int id)
function, add the accumulation code and display it in the text control.Compile and run
Sample code
See the TimerDemo
project in Sample Code