What’s the AlarmManager used for?
The AlarmManager is used to schedule events or services at either a set time or a set interval. It’s Android’s “version” of the cron. In this case, we’re going to set an alarm for five seconds after the app is launched.
What we’re going to build
In order to use it, we’re going to create an alarm which will be called after a time interval and we will perform a task using it.
Let’s have a look at the steps to create an alarm
- Create an IntentService which will execute some task and will be triggered by a BroadcastReceiver. The example below provides you the idea of it.
1234567891011public class MyLocationUpdateService extends IntentService {public MyLocationUpdateService() {super("MyLocationUpdateService");}@Overrideprotected void onHandleIntent(Intent intent) {// Perform your task here}} - Create a BroadcastReceiver which will monitor the alarm triggering and execute the IntentService for you according to it. Look at the below given example
12345678910public class MyAlarmReceiver extends BroadcastReceiver {public static final int REQUEST_CODE = 12345;// Triggered by the Alarm periodically (starts the service to run task)@Overridepublic void onReceive(Context context, Intent intent) {Intent i = new Intent(context, MyLocationUpdateService.class);context.startService(i);}} - Now we will schedule the alarm. The minimum time interval for the alarm is 60 seconds because below this time interval the alarm will consume a lot of battery.
12345678Intent intent = new Intent(context.getApplicationContext(), MyAlarmReceiver.class);final PendingIntent pIntent = PendingIntent.getBroadcast(context, MyAlarmReceiver.REQUEST_CODE,intent, PendingIntent.FLAG_UPDATE_CURRENT);long firstMillis = System.currentTimeMillis(); // alarm is set right awayAlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);if (alarm != null) {alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, firstMillis, 60000, pIntent);} - And to cancel the alarm.
1234567Intent intent = new Intent(context.getApplicationContext(), MyAlarmReceiver.class);final PendingIntent pIntent = PendingIntent.getBroadcast(context, MyAlarmReceiver.REQUEST_CODE,intent, PendingIntent.FLAG_UPDATE_CURRENT);AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);if (alarm != null) {alarm.cancel(pIntent);}
This is all you need to do to create an alarm and perform your task. It will be triggered after the time period specified automatically.
Thank you very much. This is Vedesh Kumar signing off.