Search code examples
javaandroidalarmmanagerandroid-pendingintentandroid-broadcastreceiver

AlarmManager not always executing


I'm developing an android app that sends every 5 minutes a post to a server so this way, the server can check if the phone has or not connection.

I'm using AlarmManager, sending a broadcast PendingIntent to a BroadcastReceiver which sends a post to a server. The issue is that it is not always executing:

Intent myIntent = new Intent(Inicio.this, NetworkStatusReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Inicio.this,
                                                         0,
                                                         myIntent,
                                                         0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 60000*5;
manager.setRepeating(AlarmManager.RTC_WAKEUP,
                     System.currentTimeMillis(),
                     interval,
                     pendingIntent);

Is the AlarmManager class the right way to do this?

Because I've been researching about 5.0+ android versions and the power management is different from the earlier android versions. Maybe the AlarmManager.RTC_WAKEUP option is not working on 5.0+ android versions.


Solution

  • I have done some research and I've found something that seems to work. Since this morning, I implemented it and the behavior has improved very much. I realized that having a BroadcastReceiver I could just set the alarm once and set another alarm again on the BroadcastReceiver itself when the alarm was being triggered.

    I also used the flag PendingIntent.FLAG_UPDATE_CURRENTfor the PendingIntent(since the alarm PendingIntent can be triggered from different activities)

    The code for the Activity would be something like this:

    Intent myIntent = new Intent(context, NetworkStatusReceiver.class);
        final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        final AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + timeInMillis, pendingIntent);
    

    And the code for the BroadcastReceiver.OnReceive() method would be the same code so the alarm triggers every System.currentTimeMillis() + timeInMillis again (creating this way the setRepeating() method)

    This way it seems that the alarm is always triggered since (I think) set() method from AlarmManager works fine with any android version.