Using a broadcast receiver to run AlarmManager in Android?

I am writing a program that launches the intention to periodically start the service, for this I decided to use the alarmmanager, I was able to make it do what I wanted in the activity quite easily, but Im getting an error when trying to do this in the receiver, which Im could not understand.

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);

tells me that ALARM_SERVICE cannot be resolved by a variable

here is my complete code for this 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); } } 
+4
source share
2 answers

Try

 AlarmManager am = (AlarmManager)context.getSystemService(Service.ALARM_SERVICE); 
+9
source

I found that if you are in a fragment, you can do it

 AlarmManager am = (AlarmManager)getActivity().getSystemService(Service.ALARM_SERVICE); 
+1
source

Source: https://habr.com/ru/post/1400219/


All Articles