I have an IntentService that is initially started with the click on a button:
Intent intent = new Intent(this, ProximityService.class);
intent.putExtra("com.hybris.proxi.triggerTime", 5000l);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
long trigger = System.currentTimeMillis() + (5*1000);
alarmManager.set(AlarmManager.RTC_WAKEUP, trigger, pendingIntent);
This works nicely. But then I am trying to execute the same intentservice again, from within the intentservice. The idea here is that I can vary the next execution time to save battery.
@Override
protected void onHandleIntent(Intent intent) {
Log.d("demo", "ProximityService... STARTING");
Log.d("demo", "Intent has extra with key com.hybris.proxi.triggerTime" + intent.hasExtra("com.hybris.proxi.triggerTime"));
long lastTriggerTime = intent.getLongExtra("com.hybris.proxi.triggerTime", -1);
Log.d("demo", "Last trigger time: " + lastTriggerTime);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//trigger me again - TODO change this based on closeness to store
//TODO does not work, somehow triggertime is not incremented
if (lastTriggerTime < 50000)
{
long newTriggerTime = lastTriggerTime * 2;
Intent serviceIntent = new Intent(this, ProximityService.class);
serviceIntent.putExtra("com.hybris.proxi.triggerTime", (long)newTriggerTime);
Log.d("demo","New triggerTime set in new intent is : " + serviceIntent.getLongExtra("com.hybris.proxi.triggerTime", -1));
PendingIntent pendingIntent = PendingIntent.getService(this, 0, serviceIntent, 0);
long trigger = System.currentTimeMillis() + newTriggerTime;
alarmManager.set(AlarmManager.RTC_WAKEUP, trigger, pendingIntent);
Log.d("demo", "Alarm was set with trigger time " + newTriggerTime);
}
else {
Log.d("demo", "Not rescheduling alarm: lastTriggerTime is " + lastTriggerTime);
}
Log.d("demo", "ProximityService... DONE");
}
The problem is that
intent.getLongExtra(“com.hybris.proxi.triggerTime”, -1);
always returns the initial value 5000 – so the next alarm is not scheduled at an inceasing trigger time. Somehow, the setting of the intent extra for the new trigger time does not work…
Any ideas?
You need to Use
PendingIntent.FLAG_UPDATE_CURRENTChange your code from
PendingIntent pendingIntent = PendingIntent.getService(this, 0, serviceIntent, 0);to