Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a broadcast receiver to start AlarmManager in Android?

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);

}
}
like image 332
Edmund Rojas Avatar asked Dec 27 '22 04:12

Edmund Rojas


2 Answers

Try

AlarmManager am = (AlarmManager)context.getSystemService(Service.ALARM_SERVICE);
like image 155
Rasive Avatar answered Dec 29 '22 17:12

Rasive


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

AlarmManager am = (AlarmManager)getActivity().getSystemService(Service.ALARM_SERVICE);
like image 28
Henry Avatar answered Dec 29 '22 17:12

Henry