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:
<service android:name=".chapter6.SMSDispatcherIntentService" > </service>
We almost certainly want our Service to do its work off the main thread, so sending work to an IntentService
this way seems ideal, and an IntentService
will also...