Android Programming Tutorials

(Romina) #1
Now, Your Friends Are Alarmed

Next, add a couple of private data members, one for an AlarmManager and


one for a PendingIntent, with suitable imports:


private PendingIntent pi=null;

You will need to add an import for android.app.AlarmManager. The


AlarmManager is the gateway to scheduled tasks in Android, while the


PendingIntent will be invoked each time the alarm goes off.


Then, update onCreate() to obtain the AlarmManager system service and to


set up the PendingIntent that AlarmManager should invoke every polling


cycle, plus schedule the initial alarm:


public void onCreate() {
super.onCreate();

registerReceiver(onBatteryChanged,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

alarm=(AlarmManager)getSystemService(Context.ALARM_SERVICE);

Intent i=new Intent(this, OnAlarmReceiver.class);

pi=PendingIntent.getBroadcast(this, 0 , i, 0 );
setAlarm(INITIAL_POLL_PERIOD);
}

@Override

Note that we also get rid of our statement to schedule the threadBody


Runnable as a background thread, because an IntentService (parent class of


WakefulIntentService) automatically lets us do our work on a background


thread.


This requires a setAlarm() method to actually schedule the alarm:


private void setAlarm(long period) {
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()+period,
pi);
}

292
Free download pdf