Android -- Scheduling Repeating Alarms Learning

Source: Internet
Author: User

Address: http://developer.android.com/training/scheduling/alarms.html

Alarms (based onAlarmManagerClass) give you a way to perform time-based operations outside the lifetime of your application. for example, you can use an alarm to initiate a long-running operation, such as starting a service once a day to download a weather forecast ..

In addition to your application life cycle, Alarms (based onAlarmManager class) Provides you with a method to perform some basic operations. For example, you can use an alarm to initiate a long-running operation. For example, you can enable the service once a day to download the weather forecast.

Alarms have these characteristics :( Alarms has the following features :)

  • They let you fire Intents at set times and/or intervals. allows you to initiate Intent at a scheduled or interval.
  • You can use them in conjunction with broadcast receivers to start services and perform other operations. It can be used with broadcast receivers to enable services or perform other operations.
  • They operate outside of your application, so you can use them to trigger events or actions even when your app is not running, and even if the device itself is asleep. this operation is outside your application, so when your app is not running, you can use them to trigger some events or operations, or even device sleep.
  • They help you to minimize your app's resource requirements. You can schedule operations without relying on timers or continuously running background services. help you minimize app resource requirements. You can perform scheduled operations without relying on the timer or continuously running background services.

  • Note:For timing operations that are guaranteed to occurDuringThe lifetime of your application, instead consider usingHandlerClass in conjunctionTimerAndThread. This approach gives Android better control over system resources can also ensure scheduled operations during the running of your application, without the need to consider using Handler and timer threads together. This method enables Android to better control system resources.

    Understand the Trade-offs

    A repeating alarm is a relatively simple mechanic with limited flexibility. it may not be the best choice for your app, unless you need to trigger network operations. A poorly designed alarm can cause battery drain and put a significant load on servers. repeat alarm is a flexible, limited, and relatively simple mechanism. If you need to trigger network operations, it may not be the best choice for your app. Poorly designed alarm can cause battery consumption and increase server load.

    A common scenario for triggering an operation outside the lifetime of your app is syncing data with a server. this is a case where you might be tempted to use a repeating alarm. but if you own the server that is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with sync adapter is a better solutionAlarmManager. A sync adapter gives you all the same scheduling optionsAlarmManager, But it offers you significantly more flexibility. for example, a sync cocould be based on a "new data" message from the server/device (see Running a Sync Adapter for details), the user's activity (or inactivity ), the time of day, and so on. see the linked videos at the top of this page for a detailed discussion of when and how to use GCM and sync adapter.

    Best practices

    Every choice you make in designing your repeating alarm can have consequences in how your app uses (or abuses) system resources. for example, imagine a popular app that syncs with a server. if the sync operation is based on clock time and every instance of the app syncs at 11: 00 p. m ., the load on the server cocould result in high latency or even "denial of service. "Follow these best practices in usi Ng alarms: each choice you make when designing a duplicate alert clock has a result: use (or misuse) system resources in your application. For example, imagine that a large number of apps use one server for synchronization. If the synchronization operation is based on the clock time and every app is synchronized at eleven o'clock P.M., this will lead to high service latency, or even a load rejection service. Follow the following best practices when using alams:

    • Add randomness (jitter) to any network requests that trigger as a result of a repeating alarm: Repeat the alarm to randomly trigger network requests.
      • Do any local work when the alarm triggers. "Local work" means anything that doesn't hit a server or require the data from the server. when triggered by alarm, it only works locally (Do any local work). "Local work" means that you Do not need to shake hands with the server or request server data.
      • At the same time, schedule the alarm that contains the network requests to fire at some random period of time. Meanwhile, the random schedule contains the alarm that initiates the network request.
      • Keep your alarm frequency to a minimum. Keep alarm at the lowest frequency.
      • Don't wake up the device unnecessarily (this behavior is determined by the alarm type, as described in Choose an alarm type ). no need to wake up the device (this behavior depends on the alarm type, which is described in Choose an alarm type)
      • Don't make your alarm's trigger time any more precise than it has to be. Don't let your alarm trigger time be accurate.

        UsesetInexactRepeating()InsteadsetRepeating(). When you usesetInexactRepeating(), Android synchronizes repeating alarms from multiple apps and fires them at the same time. this operation CES the total number of times the system must wake the device, thus cing drain on the battery. as of Android 4.4 (API Level 19), all repeating alarms are inexact. note that whilesetInexactRepeating()Is an improvement oversetRepeating(), It can still overwhelm a server if every instance of an app hits the server around the same time. Therefore, for network requests, add some randomness to your alarms, as discusabove. UsesetInexactRepeating()ReplaceSetRepeating () method. When you use setInexactRepeating (), duplicate alarm from multiple Android applications and trigger them at the same time. This can reduce the total number of times the system forces a device to wake up, and thus reduce power consumption. In android4.4, all repeated alarm operations are inaccurate. Note: Although setInexactRepeating () is an improved setRepeating (), it can overwhelm a server if every instance of an application shakes the server at the same time. Therefore, as discussed above, network requests increase the randomness of alarm.

      • Avoid basing your alarm on clock time if possible. if possible, Avoid clock time-based alarms (alarm ).

        Repeating alarms that are based on a precise trigger time don't scale well. UseELAPSED_REALTIMEIf you can. The different alarm types are described in more detail in the following section. Repeated alarms based on precise trigger time is not well extended. You can use ELAPSED_REALTIME. The following sections describe different alarm types in more detail.


        Set a Repeating Alarm

        As described abve, repeating alarms are a good choice for scheduling regular events or data lookups. A repeating alarm has the following characteristics: as described above, it is A good choice for regular scheduled events or repeated data query alarms. Repeated alarms have the following features:

        • A alarm type. For more discussion, see Choose an alarm type. For more information, see Choose an alarm type.
        • A trigger time. If the trigger time you specify is in the past, the alarm triggers immediately. A trigger time, If your specified trigger time is past, this alarm is triggered immediately.
        • The alarm's interval. For example, once a day, every hour, every 5 seconds, and so on. alarm interval. For example, once a day, once an hour, once every five minutes, etc.
        • A pending intent that fires when the alarm is triggered. when you set a second alarm that uses the same pending intent, it replaces the original alarm. the intent to be processed will be started when the alarm is triggered. When you set the second alarm with the same intent, it replaces the original alarm. Choose an alarm type

          One of the first considerations in using a repeating alarm is what its type should be. the first question you should consider when using the repeated alarm clock is what type you should use

          There are two general clock types for alarms: "elapsed real time" and "real time clock" (RTC ). elapsed real time uses the "time since system boot" as a reference, and real time clock uses UTC (wall clock) time. this means that elapsed real time is suited to setting an alarm based on the passage of time (for example, an alarm that fires every 30 seconds) since it isn' t affected by time zone/locale. The real time clock type is better suited for alarms that are dependent on current locale. there are two common Alarm types: "elapsed real time" and "real time clock" (RTC ). elapsed real time uses "self-system startup time" as a reference, and real time clock uses UTC (wall clock) time. This means that elapsed real time is suitable for setting an Alarm Based on time elapsed (for example, an alarm will be triggered every 30 seconds) because it will not be affected by the time zone/region. The real time clock type is more suitable for alarms that depend on the current language environment.

          Both types have a "wakeup" version, which says to wake up the device's CPU if the screen is off. this ensures that the alarm will fire at the scheduled time. this is useful if your app has a time dependency-for example, if it has a limited window to perform a particle operation. if you don't use the wakeup version of your alarm type, then all the repeating alarms will fire when your device is nex T awake. Both types have a wake-up version, that is, if the screen is off, the CPU of the wake-up device. This ensures that the alarm is enabled during the scheduled time. It is very useful if your App has time dependence. For example, there is a limited window for specific operations. If you do not use the wake-up version of the alarm, all the repeated alarms are triggered only when your device wakes up next time.

          If you simply need your alarm to fire at a particle interval (for example, every half hour), use one of the elapsed real time types. in general, this is the better choice. if you only need to start the alarm at a specific interval (for example, hourly), use elapsed real time. Generally, this is a good choice.

          If you need your alarm to fire at a participant time of day, then choose one of the clock-based real time clock types. note, however, that this approach can have some drawbacks-the app may not translate well to other locales, and if the user changes the device's time setting, it cocould cause unexpected behavior in your app. using a real time clock alarm type also does not scale well, as discussed abo Ve. we recommend that you use a "elapsed real time" alarm if you can. if you want your alarm to start at a specific time of the day, you can choose the real time clock based on the clock type. However, please note that this method may have some disadvantages, applications may not be able to be converted to other language environments, and changing the device's time settings may lead to unexpected behavior in your applications. As mentioned above, the use of real time clock alarms cannot be well extended. If possible, we recommend that you use an "elapsed real time" alarm.

          Here is the list of types: this is a list of types:

          • ELAPSED_REALTIME-Fires the pending intent based on the amount of time since the device was booted, but doesn' t wake up the device. the elapsed time between des any time during which the device was asleep. the elapsed time includes The time during device sleep.
          • ELAPSED_REALTIME_WAKEUP-Wakes up the device and fires the pending intent after the specified length of time has elapsed since device boot. after the device is started, the device is awakened for a specified time and the intention to start,
          • RTC-Fires the pending intent at the specified time but does not wake up the device. Start the intent at a specific time, but do not wake up the device
          • RTC_WAKEUP-Wakes up the device to fire the pending intent at the specified time. Wake up the device startup intention at a specific time ELAPSED_REALTIME_WAKEUP examples

            Here are some examples of usingELAPSED_REALTIME_WAKEUP. UseELAPSED_REALTIME_WAKEUP. Example

            Wake up the device to fire the alarm in 30 minutes, and every 30 minutes after that: Wake up the device and start the alarm every 30 minutes

            // Hopefully your alarm will have a lower frequency than this!alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,        AlarmManager.INTERVAL_HALF_HOUR,        AlarmManager.INTERVAL_HALF_HOUR, alarmIntent);

            Wake up the device to fire a one-time (non-repeating) alarm in one minute: Wake up the device and start the alarm one minute later, only once

            private AlarmManager alarmMgr;private PendingIntent alarmIntent;...alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);Intent intent = new Intent(context, AlarmReceiver.class);alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,        SystemClock.elapsedRealtime() +        60 * 1000, alarmIntent);
            RTC examples

            Here are some examples of usingRTC_WAKEUP. UseRTC_WAKEUP. Example

            Wake up the device to fire the alarm at approximately 2: 00 p. m ., and repeat once a day at the same time: at around two o'clock P.M., wake up the device and start the alarm, repeat once a day at the same time

            // Set the alarm to start at approximately 2:00 p.m.Calendar calendar = Calendar.getInstance();calendar.setTimeInMillis(System.currentTimeMillis());calendar.set(Calendar.HOUR_OF_DAY, 14);// With setInexactRepeating(), you have to use one of the AlarmManager interval// constants--in this case, AlarmManager.INTERVAL_DAY.alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),        AlarmManager.INTERVAL_DAY, alarmIntent);

            Wake up the device to fire the alarm at precisely a.m., and every 20 minutes thereafter: Wake up the device and start the alarm every 20 minutes after the exact AM.

            private AlarmManager alarmMgr;private PendingIntent alarmIntent;...alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);Intent intent = new Intent(context, AlarmReceiver.class);alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);// Set the alarm to start at 8:30 a.m.Calendar calendar = Calendar.getInstance();calendar.setTimeInMillis(System.currentTimeMillis());calendar.set(Calendar.HOUR_OF_DAY, 8);calendar.set(Calendar.MINUTE, 30);// setRepeating() lets you specify a precise custom interval--in this case,// 20 minutes.alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),        1000 * 60 * 20, alarmIntent);
            Decide how precise your alarm needs to be determines the exact number of your alarms

            As described abve, choosing the alarm type is often the first step in creating an alarm. A further distinction is how precise you need your alarm to be. For most apps,setInexactRepeating()Is the right choice. when you use this method, Android synchronizes multiple inexact repeating alarms and fires them at the same time. this operation CES the drain on the battery. as described above, selecting the alarm type is the first step to create an alarm. Another difference is how accurate your alarm is. SetInexactRepeating () is the right choice for most applications. When you use this method, Android synchronizes multiple inaccurate duplicate alarms and triggers them at the same time. This not only reduces the consumption of battery power.

            For the rare app that has rigid time requirements-for example, the alarm needs to fire precisely at 8: 30 a.m., and every hour on the hour thereafter-usesetRepeating(). But you shoshould avoid using exact alarms if possible. For rare applications with rigid time requirements, for example, the alarm must be accurate to AM and use setRepeating () every hour (). However, if possible, you should avoid using precise alarms.

            WithsetInexactRepeating(), You can't specify a custom interval the way you cansetRepeating(). You have to use one of the interval constants, suchINTERVAL_FIFTEEN_MINUTES,INTERVAL_DAY, And so on. SeeAlarmManagerFor the complete list. When using the setInexactRepeating () method, you cannot specify a custom interval. You can use setRepeating () to specify it. You must use one of the constant intervals, such as interval_effecteen_minutes and INTERVAL_DAY. See the complete list of AlarmManager.

            Cancel an Alarm

            Depending on your app, you may want to include the ability to cancel the alarm. To cancel an alarm, callcancel()On the Alarm Manager, passing inPendingIntentYou no longer want to fire. For example: depending on your app, you may want to cancel the alarm. Cancel an alarm, call the cancel () method in the alarm Manager, and pass in the PendingIntent object that you do not want to start again. For example:

            // If the alarm has been set, cancel it.if (alarmMgr!= null) {    alarmMgr.cancel(alarmIntent);}
            Start an Alarm When the Device Boots Device starts an Alarm When it starts

            By default, all alarms are canceled when a device shuts down. to prevent this from happening, you can design your application to automatically restart a repeating alarm if the user reboots the device. this ensures thatAlarmManagerWill continue doing its task without the user needing to manually restart the alarm. By default, when the device is disabled, all alarms will be canceled. To prevent this from happening, when a user restarts the device, you can design your program to automatically restart a repeated alarm. This ensures that the alarm manager continues its tasks without Manually restarting the alarm.

            Here are the steps: the steps below:

            1. SetRECEIVE_BOOT_COMPLETEDPermission in your application's manifest. This allows your app to receiveACTION_BOOT_COMPLETEDThat is broadcast after the system finishes booting (this only works if the app has already been launched by the user at least once ). In your application configuration file manifest, addRECEIVE_BOOT_COMPLETED permission. This allows your app to receiveACTION_BOOT_COMPLETEDEvent broadcast, which is sent after the system starts (only after your app is started at least once ).
                           
            2. ImplementBroadcastReceiverTo receive the broadcast: implements a BroadcastReceiver to receive the broadcast.
              public class SampleBootReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {            // Set the alarm here.        }    }}
            3. Add the receiver to your app's manifest file with an intent filter that filters onACTION_BOOT_COMPLETEDAction: add this receiver to your application configuration file maiifest and filter it with intent filter.ACTION_BOOT_COMPLETED event
                               
                                        
                            
                           

              Notice that in the manifest, the boot handler er is setandroid:enabled="false". This means that the specified er will not be called unless the application explicitly enables it. this prevents the boot handler er from being called unnecessarily. you can enable a receiver (for example, if the user sets an alarm) as follows: note that in the configuration file, You must set the android: enabled = "false" attribute to start the receiver. This means that the receiver will not be called unless the application explicitly enables it. This prevents unnecessary calls when the receiver is started. You can set a receiver (for example, if you set an alarm) as follows:

              ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);PackageManager pm = context.getPackageManager();pm.setComponentEnabledSetting(receiver,        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,        PackageManager.DONT_KILL_APP);

              Once you enable the caller this way, it will stay enabled, even if the user reboots the device. in other words, programmatically enabling the specified er overrides the manifest setting, even guest SS reboots. the specified er will stay enabled until your app disables it. you can disable a Explorer (for example, if the user cancels an alarm) as follows: once this method is enabled, it will remain enabled even if the user restarts the device. In other words, the receiver is programmed to overwrite the manifest, or even restarted. The receiver is enabled until your application disables it. You can disable the receiver (for example, if you cancel the alarm) as follows:

              ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);PackageManager pm = context.getPackageManager();pm.setComponentEnabledSetting(receiver,        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,        PackageManager.DONT_KILL_APP);

              If the translation is not good, please correct me. I will be very grateful and modify it in time.


Related Article

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.