With KitKat, Google changed AlarmManager such that if you wanted the Service to start at exactly set time you had to use AlarmManager new method setExact (int type, long triggerAtMillis, PendingIntent operation).
Erel implemented this in B4A as StartServiceAtExact.
Now I have upgraded to android 6.0.1 and (not) to my surprise this function is no longer accurate. I get sometimes couple of minutes (6, 7 min.) difference from the scheduled time.
This of course is the result of Google introducing a "Doze" mode.
I tried to use AlarmManager method setExactAndAllowWhileIdle (not tested yet), but searching the web I found that this doesn't fix the problems.
On stackoverflow http://stackoverflow.com/questions/33432661/alarm-manager-for-background-services I found a Java example that uses WakefulBroadcastReceiver that supposed to work in Doze mode. But I am not sure yet how to implement it. Maybe someone with more Java knowledge (or Erel) could have a look at this - i.e. how to implement WakefulBroadcastReceiver. There is also a link there to the CommonsWare website with an example on Github https://github.com/commonsguy/cwac-wakeful
The code is:
Erel implemented this in B4A as StartServiceAtExact.
Now I have upgraded to android 6.0.1 and (not) to my surprise this function is no longer accurate. I get sometimes couple of minutes (6, 7 min.) difference from the scheduled time.
This of course is the result of Google introducing a "Doze" mode.
I tried to use AlarmManager method setExactAndAllowWhileIdle (not tested yet), but searching the web I found that this doesn't fix the problems.
On stackoverflow http://stackoverflow.com/questions/33432661/alarm-manager-for-background-services I found a Java example that uses WakefulBroadcastReceiver that supposed to work in Doze mode. But I am not sure yet how to implement it. Maybe someone with more Java knowledge (or Erel) could have a look at this - i.e. how to implement WakefulBroadcastReceiver. There is also a link there to the CommonsWare website with an example on Github https://github.com/commonsguy/cwac-wakeful
The code is:
B4X:
public class PollReceiver extends WakefulBroadcastReceiver{
static final String PERIOD = "period";
@Override
public void onReceive(Context context, Intent intent){
startWakefulService(context,new Intent(context,MyService.class));
long period = intent.getLongExtra(PERIOD,-1);
if(period>0){
scheduleExactAlarm(context,(AlarmManager)context.getSystemService(Context.ALARM_SERVICE),period)
}
}
static void scheduleExactAlarm(Context context,AlarmManager alarms, long period){
Intent i = new Intent(context,PollReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context,0,i,0);
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1){
alarms.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + period,pi);
}
}