Updated 6 January 2018
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.
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.
1 2 3 4 5 6 7 8 9 10 11 |
public class MyLocationUpdateService extends IntentService { public MyLocationUpdateService() { super("MyLocationUpdateService"); } @Override protected void onHandleIntent(Intent intent) { // Perform your task here } } |
1 2 3 4 5 6 7 8 9 10 |
public class MyAlarmReceiver extends BroadcastReceiver { public static final int REQUEST_CODE = 12345; // Triggered by the Alarm periodically (starts the service to run task) @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, MyLocationUpdateService.class); context.startService(i); } } |
1 2 3 4 5 6 7 8 |
Intent 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 away AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); if (alarm != null) { alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, firstMillis, 60000, pIntent); } |
1 2 3 4 5 6 7 |
Intent 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.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.