The implementation of two kinds of Android timer

Source: Internet
Author: User

There are two kinds of timers commonly used on Android, one is java.util. Timer, one is the alarmservice of the system.


Experiment 1: Use Java.util. Timer.
Create a timer at OnStart () , update the counter every 5 seconds, and start.
Java code?
12345678 mTimer = new Timer();        mTimer.schedule(new TimerTask() {                        @Override            public void run() {                 ++mCount;                 mHandler.sendEmptyMessage(0);                            }         }, 5*1000, 5*1000);

When connected to the USB cable for debugging, it will find that everything is working properly, update the interface every 5 seconds, even if the power button is pressed, will still be triggered 5 seconds.
When the USB cable is unplugged, press the Power key to turn off the screen, after a period of time to open again, found that the timer obviously did not continue to count, stuck in the power button off the number.

Lab 2: Using Alarmservice:
2.1 A broadcast is sent by Alarmservice each 5 seconds, and the setrepeating type is alarmmanager.elapsed_realtime.
Java code?
12 AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);   am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, 5*1000, sender);

Unplug the USB cable, press the power button, open the screen again after a while, and notice that the timer does not continue to count.
2.2setRepeating Yes type set to Alarmmanager.elapsed_realtime_wakeup
Java code?
12 AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 5*1000, sender);

Unplug the USB cable, press the power button, turn on the screen a little longer, and find that the timer is counting.

In this case, the use of wakeup to ensure that the timer you want to work, but it will certainly cause increased power consumption.

The implementation of two kinds of Android timer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.