4

I am writing a program that fires off an intent to start a service periodically, to do this I have decided to use alarmmanager, I was able to make this do what I wanted in an activity fairly easily but I'm getting an error when attempting to do it in a receiver that I'm unable to figure out.

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);

tells me that ALARM_SERVICE can't be resolved to a variable

here is my complete code for that receiver:

package com.testapp21.second.activities;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;

public class PhoneOnReceiver extends BroadcastReceiver {
private PendingIntent mAlarmSender;

@Override
public void onReceive(Context context, Intent intent) {
    mAlarmSender = PendingIntent.getService(context,
              0, new Intent(context, StatsCheckerService.class), 0);

    // We want the alarm to go off 30 seconds from now.
      long firstTime = SystemClock.elapsedRealtime();

      // Schedule the alarm!
      AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
      am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                      firstTime, 30*1000, mAlarmSender);

}
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Edmund Rojas
  • 6,376
  • 16
  • 61
  • 92
  • 1
    When you say "ALARM_SERVICE can't be resolved to a variable" do you mean you get an exception at runtime or what? – Rasive Mar 07 '12 at 14:24
  • Its an error in the compiler with a red underline, I assume it has something to do with the context being different in broadcast receivers but Im not sure how to fix it – Edmund Rojas Mar 07 '12 at 14:29

2 Answers2

9

Try

AlarmManager am = (AlarmManager)context.getSystemService(Service.ALARM_SERVICE);
Rasive
  • 1,143
  • 1
  • 8
  • 20
1

I found that if you are in a fragment you can do this

AlarmManager am = (AlarmManager)getActivity().getSystemService(Service.ALARM_SERVICE);
Henry
  • 1,041
  • 1
  • 14
  • 14