There are two commonly used timers on Android: Java. util. timer and alarmservice.
Experiment 1: use Java. util. Timer.
Create a timer in onstart (), update the counter every 5 seconds, and start. Java code
- Mtimer = new timer ();
- Mtimer. Schedule (New timertask (){
- @ Override
- Public void run (){
- ++ Mcount;
- Mhandler. sendemptymessage (0 );
- }
- }, 5*1000, 5*1000 );
When you connect to the USB cable for debugging, you will find that everything works normally and the interface is updated every 5 seconds. Even if you press the power key, it will still be triggered once every 5 seconds.
When the USB cable is unplugged, press the power button to close the screen. After a period of time, it is found that the timer does not continue counting, and the number remains when the power button is disabled.
Experiment 2: Use alarmservice:
2.1 send a broadcast every five seconds through alarmservice. The setrepeating type is alarmmanager. elapsed_realtime. Java code
- Alarmmanager AM = (alarmmanager) getsystemservice (alarm_service );
- Am. setrepeating (alarmmanager. elapsed_realtime, firsttime, 5*1000, Sender );
Unplug the USB cable and press the power button. After a while, the screen is turned on again and the timer does not continue counting.
2.2setrepeating is the type set to alarmmanager. elapsed_realtime_wakeup Java code
- Alarmmanager AM = (alarmmanager) getsystemservice (alarm_service );
- Am. setrepeating (alarmmanager. elapsed_realtime_wakeup, firsttime, 5*1000, Sender );
Unplug the USB cable, press the power button, and open the screen again later. The timer is always counting.
In this case, the use of wakeup can ensure that the timer you want is always working, but it will certainly lead to an increase in power consumption.
- Alarmtest.rar (11.9 KB)
- Downloads: 0
- Timertest.rar (11.7 KB)
- Downloads: 0