Use of Android alarm clock AlarmManager

Source: Internet
Author: User

Use of Android alarm clock AlarmManager

 

AlarmManager Introduction

  AlarmManagerThis class provides access interfaces for the system alarm service.

You can set a wake-up function for your application at a certain time in the future.

When the alarm goes off, it is actuallyThe system sends a broadcast for the alarm.The target application is automatically enabled.

The registered alarm is retained when the device is sleeping. You can choose whether to wake up the device.When the device is shut down or restarted, the alarm will be cleared..

 

TheOnReceive ()When the method is executed, Alarm Manager holdsCPU wake-up lockSo that the device does not sleep until the broadcast is completed.

Once the onReceive () method returns, Alarm Manager releases the lock, indicating that the onReceive () method may sleep after the device is executed.

If Context. startService () is called in your alarm aggreger, it is very likely that the service will sleep before the device is ready.

To prevent this situation, your BroadcastReceiver and Service must implement different wake-up locks to ensure that the device continues to run until the service is available.

 

  Note:: Alarm Manager is mainly used to run your code at a specific time, even if your application is not running at that specific time.

  Handler is more convenient and efficient for conventional timing operations (ticks, timeouts, etc.

 

In addition:Since API 19, the alarm mechanism is inaccurate., The operating system will convert the alarm clock to minimize wake-up and battery usage.

Some new APIs support strict and accurate transfer. For details, see setWindow (int, long, long, PendingIntent) and setExact (int, long, PendingIntent ).

  TargetSdkVersion before API 19, the application will continue to use the previous behaviorAll alarms are accurately transmitted when accurate transmission is required.

 

Alarm Demo

The Android Api demos contains a Demo of the alarm clock:

  Com. example. android. apis. app. AlarmController

Two types of alarm clocks are set, one for one time and the other for repetition.

Declaration in Manifest, process attribute

The custom receiver is declared as follows in manifest:

        <receiver            android:name=".OneShotAlarm"            android:process=":remote" />        <receiver            android:name=".RepeatingAlarm"            android:process=":remote" />

 

The onReceive methods of the two Reducers in the Demo show their respective Toast prompts, so they are not listed.

Here to discussProcessAttribute, which specifies the process in which the component (activity, service, or consumer ER) is located.

Generally, this attribute is not specified. All components of an application run in the default process of the application. The process name is the same as the package name of the application.

For example, manifest package = "com. example. helloalarm", the default process name is com. example. helloalarm.

  <Application>You can set a different default process for all components.

Components can override the default process settings, so that your application can be multi-process.

 

If your process attributesStart with a colon, The process name will be appended with the colon string after the original process name as the new process name. This process is automatically created when the component is required. This process is a private process of the application.

If the process attributeStarts with a lowercase letter.The process name in the attribute is directly used as the process name, which is a global process. Such a process can be shared by multiple components in different applications.

 

One-time alarm

            // When the alarm goes off, we want to broadcast an Intent to our            // BroadcastReceiver. Here we make an Intent with an explicit class            // name to have our own receiver (which has been published in            // AndroidManifest.xml) instantiated and called, and then create an            // IntentSender to have the intent executed as a broadcast.            Intent intent = new Intent(AlarmController.this, OneShotAlarm.class);            PendingIntent sender = PendingIntent.getBroadcast(                    AlarmController.this, 0, intent, 0);            // We want the alarm to go off 10 seconds from now.            Calendar calendar = Calendar.getInstance();            calendar.setTimeInMillis(System.currentTimeMillis());            calendar.add(Calendar.SECOND, 10);            // Schedule the alarm!            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

 

Repeated alarm clock

Alarm settings:

            // When the alarm goes off, we want to broadcast an Intent to our            // BroadcastReceiver. Here we make an Intent with an explicit class            // name to have our own receiver (which has been published in            // AndroidManifest.xml) instantiated and called, and then create an            // IntentSender to have the intent executed as a broadcast.            // Note that unlike above, this IntentSender is configured to            // allow itself to be sent multiple times.            Intent intent = new Intent(AlarmController.this,                    RepeatingAlarm.class);            PendingIntent sender = PendingIntent.getBroadcast(                    AlarmController.this, 0, intent, 0);            // We want the alarm to go off 10 seconds from now.            Calendar calendar = Calendar.getInstance();            calendar.setTimeInMillis(System.currentTimeMillis());            calendar.add(Calendar.SECOND, 10);            // Schedule the alarm!            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);            am.setRepeating(AlarmManager.RTC_WAKEUP,                    calendar.getTimeInMillis(), 10 * 1000, sender);

 

Cancel alarm:

            // Create the same intent, and thus a matching IntentSender, for            // the one that was scheduled.            Intent intent = new Intent(AlarmController.this,                    RepeatingAlarm.class);            PendingIntent sender = PendingIntent.getBroadcast(                    AlarmController.this, 0, intent, 0);            // And cancel the alarm.            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);            am.cancel(sender);

 

AlarmManager description

The AlarmManager class provides access interfaces for the system alarm service.

It is obtained throughSystem Service:

Context. getSystemService (Context. ALARM_SERVICE ).

 

Related methods:

The cancel (PendingIntent operation) method will cancel any alarms that match the Intent.

For Intent matching, view the description of the filterEquals (Intent other) method. We can see that the two intents are consistent from the Intent resolution (filtering) (intent resolution or filtering) perspective, that is, the two intents are considered equal. That is to say, Intent's action, data, type, class, categories are the same, and other data is not within the scope of comparison.

 

The set (int type, long triggerAtMillis, PendingIntent operation) method sets an alarm.

Note: Handler may be more efficient and simple for timing operations.

  Note the following when setting an alarm:

1. If the declared triggerAtMillis is a past time, the alarm will be triggered immediately.

2. If an alarm with the same intent has been set, the previous alarm will be canceled and replaced by the new alarm.

 

Note that the intent mentioned here also means that the Intent matches with the filterEquals (Intent) Definition.

The alarm clock is a broadcast, which must be defined and registered by the receiver. The registration uses dynamic registration (registerReceiver (BroadcastReceiver, IntentFilter) or static registration (<receiver ER> tag in an AndroidManifest. xml file.

The setRepeating (int type, long triggerAtMillis, long intervalMillis, PendingIntent operation) method sets a repetitive alarm.

An interval parameter is longer than the set method.

 

There are four types:

ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC, RTC_WAKEUP.

The difference is the time standard and whether the device is awake during sleep.

For more information, see the official documentation.

 

Instance

For example, you need to set a recurring alarm to wake up at every night:

    private static final int INTERVAL = 1000 * 60 * 60 * 24;// 24h//...        Intent intent = new Intent(context, RequestAlarmReceiver.class);        PendingIntent sender = PendingIntent.getBroadcast(context,                REQUEST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);        // Schedule the alarm!        AlarmManager am = (AlarmManager) context                .getSystemService(Context.ALARM_SERVICE);        Calendar calendar = Calendar.getInstance();        calendar.set(Calendar.HOUR_OF_DAY, 21);        calendar.set(Calendar.MINUTE, 30);        calendar.set(Calendar.SECOND, 10);        calendar.set(Calendar.MILLISECOND, 0);        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),                INTERVAL, sender);

 

 

References

AlarmManager:

Http://developer.android.com/reference/android/app/AlarmManager.html

 

Alarm Demo analysis:

Http://blog.csdn.net/mapdigit/article/details/7644134

 

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.