In this tutorial, we’ll be discussing AlarmManager and Broadcast Receiver and see how to trigger a Background Service using them in our Android Application.

AlarmManager Broadcast Receiver Service

An AlarmManager is used to trigger some code at a specific time. It uses the Android SDK’s alarm service and runs independently of the application’s lifecycle.

To start an Alarm Manager you need to first get the instance from the System. Then pass the PendingIntent which would get executed at a future time that you specify.

There are different types of Alarm Manager that can be invoked:

  • setInExactAndRepeating – This doesn’t trigger the alarm at the exact time.
  • setExact – Setting an alarm manager using this ensures that the OS triggers the alarm at almost the exact time.
  • setExactAndAllowWhileIdle – This method came up with Android M. These types of alarms are allowed to get executed even in low power modes.

You need to be careful while using the Alarm Manager since they can consume battery if not handled properly.
Normally, an alarm manager cannot repeat before a minute. Also in low power mode, the duration can increase to up to 15 minutes.

Broadcast Receivers listen to system-wide and application events.
In order to trigger a Broadcast Receiver when the system is rebooted, you need to call ACTION_BOOT_COMPLETED.

In the following section, we’ll be showing how to use an Alarm Manager to trigger a Broadcast Receiver which ultimately calls a background service.

Project Structure

android-alarm-broadcast-service-project

 

Android Alarm Broadcast Service Project

Code

You need to register your Broadcast Receiver and Service in the AndroidManifest.xml as shown below:

In order to ensure that the Broadcast Receiver gets triggered properly on reboot in Android N and above, you need to set the directBootAware to be true and LOCKED_BOOT_COMPLETED

The code for the activity_main.xml layout is given below:

The code for the MainActivity.java is given below:

The code for the MyBroadcastReceiver.java file is given below:

We trigger the Service when the phone is rebooted. Inside the Service, we start a repeating alarm.
The code for the MyService.java class is given below:

The output of the above application in action is given below:

Android Alarm Broadcast Service Output

Android Alarm Broadcast Service Output

That brings an end to this tutorial. You can download the project from the link below:

By admin

Leave a Reply

%d bloggers like this: