AlarmManager is not repeating

2

I have an alarm that is triggered every 5 minutes, and it calls an intentService to test a condition that if true, sends notification to the user, otherwise it does nothing.

But the intentService is only being called once, and only if I open the application (even if I open it do I need to reopen), I even put it to send a notification in case the condition is false to be sure that it is the alarmManager that is not repeating itself.

public class AlarmMgr {
    AlarmManager alarmMgr;
    public void Alarm(Context context) {
            // Set the alarm here.
            PendingIntent alarmIntent;

            alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intentA = new Intent(context, BlockFoundService.class);
            alarmIntent = PendingIntent.getBroadcast(context, 0, intentA, PendingIntent.FLAG_UPDATE_CURRENT);

            // setRepeating() lets you specify a precise custom interval--in this case,
            alarmMgr.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
                    1000 * 60 * 5 , alarmIntent);
    }
    public void CancelAlarm (Context context){
        if (alarmMgr!= null) {
            Intent intentA = new Intent(context, BlockFoundService.class);
            PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intentA, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmMgr.cancel(alarmIntent);
        }
    }
}
    
asked by anonymous 05.03.2018 / 18:35

1 answer

1

In this way the alarm can not ever launch the IntentService.

You are building PendingIntent with PendingIntent.getBroadcast() , which serves to launch Broadcast Receivers. To launch a Service you must use PendingIntent.getService() .

Replace

alarmIntent = PendingIntent.getBroadcast()(context, 0, intentA, PendingIntent.FLAG_UPDATE_CURRENT);

by

alarmIntent = PendingIntent.getService(context, 0, intentA, PendingIntent.FLAG_UPDATE_CURRENT);
    
05.03.2018 / 19:06