Android Programming Tutorials

(Romina) #1
Now, Your Friends Are Alarmed

To obtain the JAR containing WakefulIntentService, you can either


download the source code from its GitHub repository and run ant jar to


build it, or you can download a pre-compiled JAR from that GitHub


repository's "Downloads" area, or you can get the JAR out of the source


code for this book in the 30-SysSvcs edition of the Patchy project.


Either way, once you have the JAR, put it in your libs/ directory.


Step #2: Create a Layout....................................................................


In order to receive alarms from the AlarmManager, we need a


BroadcastReceiver registered in our AndroidManifest.xml file. This


BroadcastReceiver, in turn, needs to start our PostMonitor service, in case it


is not running, and to let it know that a poll is required.


Create Patchy/src/apt/tutorial/two/OnAlarmReceiver.java with the


following implementation:


package apt.tutorial.two;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.commonsware.cwac.wakeful.WakefulIntentService;

public class OnAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

Intent i=new Intent(context, PostMonitor.class);

i.setAction(PostMonitor.POLL_ACTION);

WakefulIntentService.sendWakefulWork(context, i);
}
}

Then, add it to AndroidManifest.xml, along with the WAKE_LOCK permission we


need in order to use a WakeLock:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

290
Free download pdf