Implementation of the Android timer

Source: Internet
Author: User

There are two kinds of timers commonly used on Android, one is Java.util.Timer, the other 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.
mTimer = newTimer();       
mTimer.schedule(newTimerTask() {           
            @Override
            publicvoidrun() {
                ++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.
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
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 use mechanism of Alarmmanager is called the global timer, and some call it an alarm clock. Through the use of it, the personal feel called the global timer is more appropriate, in fact, its role and timer a bit similar. There are two similar usages: (1) Perform an action after a specified length of time (2) perform an operation periodically

Alarmmanager objects are used in conjunction with intent, you can start an activity on a timed basis, send a broadcast, or open a service.

The following code describes the use of two timing methods in detail:

(1) Perform an action after a specified length of time

Java code
  1. //action: Send a broadcast, broadcast after receiving, toast prompt timed operation completed
  2. <!--
  3. Code highlighting produced by Actipro Codehighlighter (freeware)
  4. http://www.codehighlighter.com/
  5. --Intent Intent =new Intent (Main. This, alarmreceiver.  class);
  6. Intent.setaction ("short");
  7. Pendingintent sender=
  8. Pendingintent.getbroadcast (Main.   This, 0, intent, 0);
  9. //Set a time after five seconds
  10. Calendar calendar=calendar.getinstance ();
  11. Calendar.settimeinmillis (System.currenttimemillis ());
  12. Calendar.add (Calendar.second, 5);
  13. Alarmmanager alarm= (Alarmmanager) Getsystemservice (Alarm_service);
  14. Alarm.set (Alarmmanager.rtc_wakeup, Calendar.gettimeinmillis (), sender);
  15. //or simplified in the following way
  16. //alarm.set (Alarmmanager.rtc_wakeup, System.currenttimemillis () +5*1000, sender);
  17. Toast.maketext (Main.   This, "alarm open after five seconds", Toast.length_long). Show ();

Note: Receiver remembers registering in Manifest.xml

Java code
  1. <!--
  2. Code highlighting produced by Actipro Codehighlighter (freeware)
  3. http://www.codehighlighter.com/
  4. - public static class Alarmreceiver extends broadcastreceiver{
  5. @Override
  6. public void OnReceive (context context, Intent Intent) {
  7. //TODO auto-generated method stub
  8. if (intent.getaction (). Equals ("short")) {
  9. Toast.maketext (Context, "short alarm", Toast.length_long). Show ();
  10. }else{
  11. Toast.maketext (context, "repeating alarm",
  12. Toast.length_long). Show ();
  13. }
  14. }
  15. }

(2) Periodic execution of an operation

Java code
  1. <!--
  2. Code highlighting produced by Actipro Codehighlighter (freeware)
  3. http://www.codehighlighter.com/
  4. --Intent Intent =new Intent (Main. This, alarmreceiver.  class);
  5. Intent.setaction ("repeating");
  6. Pendingintent sender=pendingintent
  7. . Getbroadcast (Main.   This, 0, intent, 0);
  8. //Start time
  9. long Firstime=systemclock.elapsedrealtime ();
  10. Alarmmanager am= (Alarmmanager) Getsystemservice (Alarm_service);
  11.   5 seconds, one cycle, no stop sending broadcasts.
  12. Am.setrepeating (alarmmanager.elapsed_realtime_wakeup
  13. , Firstime, 5*,sender);

Alarmmanager's setrepeating () is equivalent to a timer's schedule (task,delay,peroid); a bit of a difference where the timer this method is to specify how long to delay

Start the periodic execution task later;

Alarmmanager Cancellation: (It is important to note that the canceled intent must be in absolute agreement with the startup intent to support the cancellation Alarmmanager)

Java code
  1. <!--
  2. Code highlighting produced by Actipro Codehighlighter (freeware)
  3. http://www.codehighlighter.com/
  4. --Intent Intent =new Intent (Main. This, alarmreceiver.  class);
  5. Intent.setaction ("repeating");
  6. Pendingintent sender=pendingintent
  7. . Getbroadcast (Main.   This, 0, intent, 0);
  8. Alarmmanager alarm= (Alarmmanager) Getsystemservice (Alarm_service);
  9. Alarm.cancel (sender);

Implementation of the 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.