I want to perform a database operation at specific moments in time and use an alarm manager and a pending intent in conjunction with a broadcast receiver.
This works, but when there are multiple intents that the same broadcast receiver has to receive within a short timeframe (f.ex. within a minute), onreceive() only gets called once.
Intent intent2 = new Intent(this, CustomBroadcastReceiver.class);
intent2.putExtra("taskId", currentTask.getTaskId());
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
((long) dataSource.fetchTask(task.getTaskId()).getTaskTime() * 60 * 1000), pendingIntent1);
and the onreceive method of the broadcastreceiver:
@Override
public void onReceive(Context context, Intent intent) {
dataSource = new DataSourceClass(context);
dataSource.open();
int taskId = intent.getIntExtra("taskId", 0);
dataSource.setTaskStatus(3, taskId);
dataSource.setCatInActive(dataSource.fetchTask(taskId).getTaskCategory())
}
Any suggestions on what I'm doing wrong?
Instead of set()
you can use setExact()
after KITKAT:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
}
The second parameter in getBroadcast()
is the requestCode, which works as if it was an ID, so, each PendingIntent should have a unique requestCode (aka ID). All your pendingIntent1
's have the same requestCode (0), I'm not sure if that's what's causing the issue but it could be, you can set a diffrent requestCode for each pendingIntent like this:
int i = sharedPrefs.getInt("i", 0);
Intent intent2 = new Intent(this, CustomBroadcastReceiver.class);
intent2.putExtra("taskId", currentTask.getTaskId());
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, i++, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
((long) dataSource.fetchTask(task.getTaskId()).getTaskTime() * 60 * 1000), pendingIntent1);
sharedPrefs.edit.putInt("i", i).apply();