Use of Android AlarmManager alarm clock

Keywords: Attribute Android xml

Introduction to AlarmManager

The AlarmManager class provides an interface to the system alarm service.

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

When the alarm clock rings, the system actually sends out a broadcast registered for the alarm clock, which will automatically turn on the target application.

The registered alarm clock will remain when the device is sleeping. You can set whether to wake up the device selectively. However, when the device is powered off and restarted, the alarm clock will be cleared.

When the onReceive() method of the alarm receiver is executed, the Alarm Manager holds a CPU wake-up lock, which ensures that the device will not sleep until the broadcast is processed.

Once the onReceive() method returns, Alarm Manager releases the lock, indicating that in some cases, the device may sleep as soon as the onReceive() method finishes executing.

If you call Context.startService() in your alarm receiver, it is very likely that service will not be ready before the device is sleep.

To prevent this, your BroadcastReceiver and service need to implement different wake-up locking mechanisms 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 does not run at that specific time.

For the regular timing operations (ticks, timeouts, etc), it is more convenient and efficient to use the Handler.

Another: starting from API 19, the mechanism of alarm is inaccurate transmission. The operating system will switch the alarm clock to minimize wake-up and battery use.

Some new API s support strict and accurate delivery, as shown in setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent).

The application of targetSdkVersion before API 19 will continue to use the previous behavior, and all alarm clocks will be delivered accurately when accurate delivery is required.

Alarm clock Demo

Android Api demos has a Demo about the use of alarm clock:

com.example.android.apis.app.AlarmController

There are two alarm clocks, one is disposable, the other is repetitive.

Declaration in Manifest, process attribute

The custom receiver is declared as follows in the manifest:
Copy code


Copy code

The onReceive methods of the two receivers in Demo display their Toast prompts, so they are not listed.

Here we discuss the process attribute, which specifies the process of the component (activity, service, receiver, etc.).

Generally, this property is not specified. All components of an application run in the default process of the application. The process name is consistent with the package name of the application.

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

The process attribute of the element sets a different default process for all components.

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

If your process property starts with a colon, the process name will be followed by the original process name with a string after the colon as the new process name. This process is created automatically when the component needs to. This process is an application private process.

If the process attribute starts with a lowercase letter, it will directly use the name in the attribute as the process name, which is a global process, so that the process can be shared by multiple components in different applications.

Disposable alarm clock
Copy code

    // 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);

Copy code

Repeating alarm clock

Alarm settings:
Copy code

    // 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);

Copy code

Alarm cancel:
Copy code

    // 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);

Copy code

AlarmManager description

The AlarmManager class provides an interface to the system alarm service.

It is acquired through system services:

Context.getSystemService(Context.ALARM_SERVICE).

Relevant method description:

The canceling (pendingintent operation) method will cancel any alarm clock matching the Intent.

For the matching of Intent, look at the description of the filterEquals(Intent other) method. It can be seen that the two Intent are the same from the perspective of Intent resolution (filtering), that is, they are considered equal. That is to say, the action, data, type, class and categories of Intent are the same, and other data are not within the scope of comparison.

The set (int type, long trigger at millis, pendingintent operation) method will set an alarm clock.

Note: for timing operations, it may be more efficient and simple to use the Handler.

Note when setting the alarm clock:

1. If the declared trigger at millis is a past time, the alarm will be triggered immediately.

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

Note that the same meaning of intent here refers to the matching of intent under the definition of filter equals (intent).

The alarm clock is a broadcast. The receiver needs to define and register by itself. The registration can use either dynamic registration (register receiver (broadcast receiver, intentfilter)) or static registration (tag in an Android manifest. XML file).

The setrepeating (int type, long trigger at millis, long interval millis, pendingintent operation) method will set a repetitive alarm clock.

There is one more interval parameter than the set method.

There are four types of type:

ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC, RTC_WAKEUP.

What distinguishes is the time standard and whether to wake up the device in the sleep state.

Please refer to the official documents for details.

Example

For example, set a repeated alarm clock to wake up at 21:30 every night:
Copy code

    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);
Published 213 original articles, won praise 2, visited 6046
Private letter follow

Posted by miesemer on Tue, 03 Mar 2020 23:28:59 -0800