Working Alarm Manager code, Android

AlarmManager is a pain to get working. It took me a while to get it up and running. This is what I have in my code now, running.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent notifyintent = new Intent(this, OnAlarmReceiver.class);
PendingIntent notifysender = PendingIntent.getBroadcast(this, 0, notifyintent,
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 20 * 1000,


public class OnAlarmReceiver extends BroadcastReceiver {
     public void onReceive(Context context, Intent intent) {
        // PullPendingRequests.acquireStaticLock(context)
        try {
            lock = getLock(context);
        context.startService(new Intent(context, UpdateCustomerRequests.class));
        } finally {
            if (lock.isHeld()) {

private static final String NAME = "com.commonsware.cwac.wakeful.WakefulIntentService";
private static volatile PowerManager.WakeLock lockStatic = null;
private static PowerManager.WakeLock lock;

synchronized private static PowerManager.WakeLock getLock(Context context) {
    if (lockStatic == null) {
        PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NAME);
    return (lockStatic);

IntentService which is called by OnAlarmReceiver

public class UpdateCustomerRequests extends IntentService {
final protected void onHandleIntent(Intent intent) {
//Your stuff here

public class LocalBinder extends Binder {
    public UpdateCustomerRequests getService() {
        return UpdateCustomerRequests.this;

public IBinder onBind(Intent intent) {
    return bindToHomeScreen;

Android Manifest

– Inside manifest tag

<uses-permission android:name="android.permission.WAKE_LOCK" />

– Inside application tag

                android:exported="true" >
                    <action android:name="android.intent.action.NOTIFY" />

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s