Handling alarms with Services

Just like starting Activities, starting a Service from an alarm involves scheduling an appropriate PendingIntent instance, this time using the static getService method:

Intent intent = new Intent(this,SMSDispatcherIntentService.class);
intent.putExtra(SMSDispatcherIntentService.TO_KEY, phoneNumber);
intent.putExtra(SMSDispatcherIntentService.TEXT_KEY, text);
PendingIntent service = PendingIntent.getService(
   context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, time, service);

As you already know, the Service should be globally defined on the Android Manifest with a service element. Given that we are calling it explicitly using the class name, we only need to define the service class: ...

Get Asynchronous Android Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.