Android Programming Tutorials

(Romina) #1
Now, Your Friends Are Alarmed

The setAlarm() implementation tells AlarmManager to schedule a one-shot


alarm (rather than a recurring alarm), using the time-base of


SystemClock.elapsedRealtime(), to go off in period milliseconds from now,


invoking our PendingIntent at that point.


We now need to do the actual work itself. According to the protocol for


WakefulIntentService, we need to override a doWakefulWork() method, which


will be invoked inside a partial WakeLock every time the service is started.


For those that are actual polling Intents, we want to poll the Twitter


accounts, then schedule the next alarm:


@Override
protected void doWakefulWork(Intent i) {
if (i.getAction().equals(POLL_ACTION)) {
for (Account l : accounts.values()) {
poll(l);
}
}

setAlarm(isBatteryLow.get()? POLL_PERIOD* 10 : POLL_PERIOD);
}

You will recognize some of this functionality as mimicking the threadBody


Runnable that we are no longer using.


Note that while AlarmManager supports recurring alarms, since our polling


period may change based upon battery state, we are manually scheduling


successive alarms here.


We also need to cancel the outstanding alarm when the service is


destroyed:


@Override
public void onDestroy() {
super.onDestroy();

alarm.cancel(pi);
unregisterReceiver(onBatteryChanged);
}

Finally, WakefulIntentService requires a constructor, because IntentService


(supplied by Android) does. The WakefulIntentService's constructor takes a


293
Free download pdf