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();
Related
I have two pending Intent to use with Alarm Manager one is:
Intent i = new Intent(context, TriggerAlarm.class);
PendingIntent pi =PendingIntent.getBroadcast(context,0,i,PendingIntent.FLAG_CANCEL_CURRENT);
and the other is:
Intent i = new Intent(context, TriggerNotification.class);
PendingIntent pi = PendingIntent.getBroadcast(context,0, i,PendingIntent.FLAG_CANCEL_CURRENT);
I use these two in different methods in my application
my question is:
Are these pendingIntents differnt from each other?? because the intents are different but the Ids are same
If I set alarm manager for each of these pending intent do both of them trigger or one replace another?
So the easy way is test it directly by yourself.
I have tested it on my computer and here is what i got:
Are these pendingIntents different from each other?? because the intents are different but the Ids are same
-Yes they are different each other although the Ids are same
If I set alarm manager for each of these pending intent do both of them trigger or one replace another?
-Both of them will be triggered
Here are my code for test, you can copy and try it by yourself
Copy this method to your activity, and call it
private void setAlarmManager() {
Log.v("AlarmManager", "Configuring AlarmManager...");
Intent startIntent1 = new Intent(context, AlarmReceiverFirst.class);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 0, startIntent1, PendingIntent.FLAG_CANCEL_CURRENT);
Intent startIntent2 = new Intent(context, AlarmReceiverSecond.class);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 0, startIntent2, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 20);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Log.v("AlarmManager", "Starting AlarmManager for >= KITKAT version");
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent1);
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent2);
} else {
Log.v("AlarmManager", "Starting AlarmManager for < KITKAT version");
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent1);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent2);
}
Log.v("AlarmManager", "AlarmManager has been started");
}
Create your first receiver class
public class AlarmReceiverFirst extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v(this.getClass().getSimpleName(), "first alarm receiver is called");
}
}
Create your second receiver class
public class AlarmReceiverSecond extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v(this.getClass().getSimpleName(), "second alarm receiver is called");
}
}
Register those receivers to your manifest
<receiver android:name=".AlarmReceiverFirst" />
<receiver android:name=".AlarmReceiverSecond" />
Not to be confused, what you called Id here is called request code. It is used for cancelling the pending intent.
Intents are just the action PendingIntent is bound to execute once it triggers. But this triggering criteria are entirely depending on PendingIntent itself and RequestCode is playing here a pretty good role to uniquely identify, manage and trigger PendingIntent.
Therefore, no matter what the Intent is, if the requestCode is repeated then the latter PendingIntent will trigger. If you need to trigger multiple PendingIntents, the requestCode must be different from each other.
You can have same name of intents but with different ids like following,
Intent i = new Intent(context, TriggerAlarm.class);
PendingIntent pi =PendingIntent.getBroadcast(context,System.currentTimeMillis(),i,PendingIntent.FLAG_CANCEL_CURRENT);
And
Intent i = new Intent(context, TriggerNotification.class);
PendingIntent pi = PendingIntent.getBroadcast(context,System.currentTimeMillis(), i,PendingIntent.FLAG_CANCEL_CURRENT);
This way both the intents would be distinguished differently from each other and will get triggered.You can have any unique id instead of System.currentTimeMillis()
I have created a BroadCastReceiver which schedules some events using alarm manager.
In the BroadcastReceiver I am using following code to schedule.
Intent localIntent = new Intent("com.test.sample");
PendingIntent pi = PendingIntent.getBroadcast(context, 0,
localIntent, 0);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + (5 * 60 * 1000),
pi);
Here context comes from the onReceive method of the receiver.
I want to cancel this alarm on receive of other broadcast.
I am aware that alarm can be cancelled by alarmManager.cancel(pi);
However if the alarmanager was set from any other activity that how to get hold of PendingIntent to cancel it?
Thanks
You need to create a new PendingIntent with the same id then pass it as argument in cancelAlarm() method like follows:
To create alarm
int alarmId = 0; /* Dynamically assign alarm ids for multiple alarms */
Intent intent = new Intent(context, AlarmReceiver.class); /* your Intent localIntent = new Intent("com.test.sample");*/
intent.putExtra("alarmId", alarmId); /* So we can catch the id on BroadcastReceiver */
PendingIntent alarmIntent;
alarmIntent = PendingIntent.getBroadcast(context,
alarmId, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
To cancel alarm (in BroadcastReceiverwhitin onReceive(Context context, Intent intent)method)
int alarmId = intent.getExtras().getInt("alarmId");
PendingIntent alarmIntent;
alarmIntent = PendingIntent.getBroadcast(this, alarmId,
new Intent(this, AlarmReceiver.class),
PendingIntent.FLAG_CANCEL_CURRENT);
cancelAlarm(alarmIntent);
I'm testing AlarmManager to use in my app, and it is firing my Broadcast Receiver immediately when I want it to fire after 1 minute. The code is below:
public class SetMealTimersActivity extends Activity {
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_meal_timers);
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Ready to Go!", Toast.LENGTH_LONG).show();
}
};
registerReceiver(br, new IntentFilter("com.ian.mealtimer"));
pi = PendingIntent.getBroadcast(this, 0, new Intent(
"com.ian.mealtimer"), 0);
am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
60 * 1000, pi );
}
try :
am.set(AlarmManager.RTC_WAKEUP,
Calendar.getInstance().getTimeInMillis()+60*1000, pendingIntent);
it is working for me.
If using an exact alarm, make sure it's time is in the future. Otherwise it will fire immediately.
Try changing SystemClock.elapsedRealtime() to System.currentTimeMillis() and AlarmManager.ELAPSED_REALTIME_WAKEUP to AlarmManager.RTC_WAKEUP.
Try to use AlarmManager.setExact(int, long, PendingIntent) if you use Android API > 18 or compile with API < 19, because the time management for this methods changed with API 19. Maybe that helps. Read the documentation for more information.
make id for pendingIntent as this
pendingIntent = PendingIntent.getActivity(this, 999123266,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
All example
public void setAlarm_sat(int dayOfWeek1) {
cal1.set(Calendar.DAY_OF_WEEK, dayOfWeek);
Intent intent = new Intent(this, RemmemberActivity.class);
pendingIntent = PendingIntent.getActivity(this, 999123266,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Long alarmTime = cal1.getTimeInMillis();
AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP,
alarmTime,7*24 * 60 * 60 * 1000,
pendingIntent);
// am.set(AlarmManager.RTC, cal1.getTimeInMillis(), pendingIntent);
}
Intent in2 = new Intent(context, ReminderService.class);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 0, in2, 0);
AlarmManager alarmManager2 = (AlarmManager)context.getSystemService(context.ALARM_SERVICE);
alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 0, pendingIntent2);
and the reminderservice.java include the following code
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Context context = getApplicationContext();
Intent in = new Intent(this, RemindBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, in, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 1000, pendingIntent);
}
First of all I suggest you to just use only RemindBroadcastReceiver. There isn't any need of ReminderService
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 1000, pendingIntent);
Here you have set repeated alarm which triggered after every 1 second. You need to use alarmManager.set instead of alarmManager.setRepeating.
I think bellow code will be helpful for you:
/------------------- CALLING PART
Intent in2 = new Intent("MY_ALARM_ACTION");
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 0, in2, 0);
AlarmManager alarmManager2 = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
//alarmManager2.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent2);
alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (5 * 1000), AlarmManager.INTERVAL_DAY, pendingIntent2);
}
/-------------------
/-------------------------- RemindBroadcastReceiver ----------------
public class RemindBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction() == "MY_ALARM_ACTION")
{
// TODO Enter your code here
}
}
}
You didn't explain what you want this code to do so we can't really know, but these are some errors I see anyway:
I assume that ReminderService is a subclass of Service, therefore you should use PendingIntent.getService rather than PendingIntent.getBroadcast.
In the first piece of code you call setRepeatig with the parameter intervalMillis = 0, and never calling AlarmManager.cancel, which I guess is an error because Android won't trigger your alarm forever, non stop.
Why are you starting a service just so you can set another alarm to trigger something else inside it?
Please explain the purpose of your code.
In my code, I create an alarm as follows:
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent("mypackage.START_MONITORING_SERVICE");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
long timeForNextStart = System.currentTimeMillis() + elapsedTime;
am.set(AlarmManager.RTC_WAKEUP, timeForNextStart, pi);
To cancel the alarm I do this:
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent("mypackage.START_MONITORING_SERVICE");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
am.cancel(pendingIntent);
My question is whether this is the correct way to cancel ALL alarms of the same intent. The docs say:
Remove any alarms with a matching Intent. Any alarm, of any type,
whose Intent matches this one (as defined by filterEquals(Intent)),
will be canceled.
I'm not exactly sure what defines a "matching intent". If I create multiple alarms with the above code and then peform the cancel as shown, will it cancel ALL of the alarms I created?
You should use PendingIntent flag ==> PendingIntent.FLAG_CANCEL_CURRENT fourth parameters create pendingIntent instance method.
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);
Try this
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent updateServiceIntent = new Intent(context, MyPendingIntentService.class);
PendingIntent pendingUpdateIntent = PendingIntent.getService(context, 0, updateServiceIntent, 0);
// Cancel alarms
try {
alarmManager.cancel(pendingUpdateIntent);
} catch (Exception e) {
Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
}
My question is whether this is the correct way to cancel ALL alarms of
the same intent?
I dont know if you aware of requestCode should be unique in for each pendingIntent for following syntax
public static PendingIntent getService (Context context, int requestCode, Intent intent, int flags)
I'm not exactly sure what defines a "matching intent".
Each pending intent map with its provided intent to trigger and each request code map with that intent .
We can say it can be same requestcode for two different pendingIntent which ideally having two different intents .
Remember , here if PendingIntent have a same requestCode for a same intent then it can be override or cancel according to int flags
If I create multiple alarms with the above code and then peform the
cancel as shown, will it cancel ALL of the alarms I created?
To create a multiple alarm you have to give a different requestCode with the same intent .
If you want to cancel those created alarm then you have to cancel them according requestCode
For example
To Create :
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
For (int i= 0 ; i <5 ; i++){
PendingIntent contentIntent = PendingIntent.getBroadcast(TaskReminder.this, i,
new Intent(),PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeForNextStart, contentIntent);
}
To cancel :
For (int i= 0 ; i <5 ; i++){
//Note here ' i ' is the requestCode which map each pendingIntent with there provided intent
PendingIntent contentIntent = PendingIntent.getBroadcast(TaskReminder.this, i,
new Intent(),PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(contentIntent);
}