I use AlarmManager and try to give some values in putExtra to my BroadcastReceiver. The values I send go to the BroadcastReceiver, it works fine to transmit values.
But I send my variable "counter" and I always get the old values that existed on the first start of my setRepeating(). And I know that the counter values are ways more high that I see there. So when the values change nothing happens. How can I have an event every half hour with right values?!
I've searched now for 3 hours but can't find a solution to make an interaction of my AlarmManager and some values out of a Sensor...
public void startAlarm(View view) {
try {
AlarmManager alarms = (AlarmManager) this
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(),
MyAlarmReceiver.class);
intent.putExtra("startStepCounter", startStepCounter);
intent.putExtra("lastStepCounter", lastStepCounter);
final PendingIntent pIntent = PendingIntent.getBroadcast(this,
1234567, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarms.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), timeToAlarmMilli, pIntent);
} catch (Exception e) {
}
}
public class MyAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Alarm Receiver", "Entered");
//
Bundle bundle = intent.getExtras();
int local_start = bundle.getInt("startStepCounter");
int local_last = bundle.getInt("lastStepCounter");
Toast.makeText(context,
"ALARM " + local_start + " " + local_last,
Toast.LENGTH_SHORT).show();
}
}
look at this part of your code
final PendingIntent pIntent = PendingIntent.getBroadcast(this,
1234567, intent, PendingIntent.FLAG_CANCEL_CURRENT);
you need to provide uniuque id for secound part each time you use pending intent, so instead of 1234567, use a unique id.
Related
I have the below class to check if my alarms are being triggered at the exact time which I scheduled or is it differing.
I will call SetAlarm method inside the BroadCast Reciever from MainActivity. The consecutive alarms will be set by the Receiver itself by setting current time as its new string extra.
Alarms are working fine except the issue Intent string extras are not getting updated. ScheduledTime will always hold the initial value regardless of what I have set it in the setAlarm method.
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Date currentTime = new Date();
String ScheduledTime = "";
if (null != intent) { //Null Checking
ScheduledTime = intent.getStringExtra("ScheduledTime");
//intent.removeExtra("ScheduledTime");
}
String message = "Current Time" + currentTime + ", Scheduled Time was: " + ScheduledTime ;
//Show Notification
long alarmMillis =(10*60*1000) ; //Set Alarm after 10 minutes
Long newTimeInMillis = System.currentTimeMillis() + alarmMillis;
currentTime.setTime(newTimeInMillis );
setAlarm(context, newTimeInMillis , currentTime.toString());
}
public void setAlarm(Context context, Long timeMillis, String ScheduledTime)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmReceiver.class);
i.putExtra("ScheduledTime", ScheduledTime);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setExact(AlarmManager.RTC_WAKEUP, timeMillis, pi);
}
}
From Android official site
public static final int FLAG_UPDATE_CURRENT
Flag indicating that if the described PendingIntent already exists,
then keep it but replace its extra data with what is in this new
Intent. For use with getActivity(Context, int, Intent, int),
getBroadcast(Context, int, Intent, int), and getService(Context, int,
Intent, int).
This can be used if you are creating intents where only the extras
change, and don't care that any entities that received your previous
PendingIntent will be able to launch it with your new extras even if
they are not explicitly given to it.
So change your code from
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
to
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
I set an alarm from activity A then in activity B I can delete and update the alarm set in activity A. Updating of alarm is working but delete doesn't, I've already tried some answer from here but nothing seems to work.
I set my alarms like this.
public void Alarms() {
for(eventlist_model model:arrayList)
{
int id=model.getEvent_id();
String type=model.getEvent_type();
String date=model.getEvent_date();
String time=model.getEvent_time();
String note=model.getEvent_note();
SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd HH:mm");
try{
String sched=date+" "+time;
Date newSched=format.parse(sched);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(newSched);
if (calendar1.before(calendar))
calendar1.add(Calendar.DATE, 1);
Intent intent = new Intent(this, events_receiver.class).setAction("Dog_alarm");
intent.putExtra("type", type);
intent.putExtra("note", note);
intent.putExtra("id", id);
PendingIntent dog1 = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarm1 = (AlarmManager) getSystemService(ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= 19) {
alarm1.setExact(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), dog1);
} else {
alarm1.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), dog1);
}
}catch (Exception e)
{
e.printStackTrace();
}
}
}
then in activity B I use this to cancel the alarm
public void cancelTask()
{ int id=Integer.valueOf(eventid);
Intent intent = new Intent(update_task.this, events_receiver.class);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent task = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.cancel(task);
}
But it doesn't work and Im stuck here. Can anyone help me in this?
According to documentation of cancel method of AlarmManager:
void cancel (PendingIntent operation)
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.
It means if intentA detected to be equal withintentB, using filterEqauls Method, i.e. intentA.filterEquals(intentB)==true, then intentB in alarmanger can be used to cancel intentA which already set inside alarmManager.
filterEquals documentation notices:
boolean filterEquals (Intent other)
Determine if two intents are the same for the purposes of intent
resolution (filtering). That is, if their action, data, type, class,
and categories are the same. This does not compare any extra data
included in the intents.
It means it filterEquals does not care to extras inside intents to compare them but other paramters like Action should be exactly the same.
In your case, you've missed to call setAction in cancellation intent.
So you should change your cancelTask method like this:
public void cancelTask()
{ int id=Integer.valueOf(eventid);
Intent intent = new Intent(update_task.this, events_receiver.class);
intent.setAction("Dog_alarm");//<--- this is missed
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent task = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.cancel(task);
}
I thought this would solve my problem, but it doesn't.
I have this code to send my alarm:
public void triggerAlarm() {
AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(ALARM_SERVICE);
alarmManager = (AlarmManager) getContext().getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getContext(), AlarmReceiver.class);
intent.putExtra("Id", nextDue.id.get() + "");
String passed = intent.getStringExtra("Id");
Log.d("DEBRRUG", "The extra im passing: " + passed);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), i++, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, soonest.dueTime.get(), pendingIntent);
}
My DEBRRUG statement indicates that the extra being passed is 8.
This is my alarm receiver:
#Override
public void onReceive(Context context, Intent intent) {
String passed = intent.getStringExtra("Id");
Log.d("DEBRRUG", "The extra im receiving: " + passed);
}
Here, my DEBRRUG statemnt indicates that the extra im receiving is NULL.
Note: Something that could, possibly, be interesting is that my triggerAlarm method is being called from within my ContentProvider. Don't know if that helps you understand my problem better or not.
Use
intent.getExtras().getString("id")
I found it. Wow! I was sending another alarm in another area of my code, where I wasn't putting the extra on.
Doing ctrl f -> ".set(Alar" let me track down the little bastard.
I'm writing an application with multiple alarms and I want to have an option to cancel them. I'm using AlarmManager and PendingIntent. My problem is that when I want to cancel an alarm, getBroadcast don't find a PendingIntent matching the criteria.
private void turnOnMorningRemider()
{
long time = System.currentTimeMillis() + 60 * 45;
Intent tmpIntent = new Intent(this, AlarmPopUpDialog.class);
tmpIntent.putExtra(getString(R.string.alarm_time_of_day), AlarmPopUpDialog.REQUEST_CODE_MORNING);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(tmpIntent);
// Gets a PendingIntent containing the entire back stack
morningPendingIntent = stackBuilder.getPendingIntent(AlarmPopUpDialog.REQUEST_CODE_MORNING, PendingIntent.FLAG_ONE_SHOT);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, time, morningPendingIntent);
Toast.makeText(this, "Alarm is on.", Toast.LENGTH_LONG).show();
}
To cancel alarm I use:
private void turnOffMorningReminder()
{
Intent tmpIntent = new Intent(this, AlarmPopUpDialog.class);
PendingIntent pi = PendingIntent.getBroadcast(this, AlarmPopUpDialog.REQUEST_CODE_MORNING,
tmpIntent, PendingIntent.FLAG_NO_CREATE);
if (pi != null)
{
alarmManager.cancel(pi);
Toast.makeText(this, "Alarm is off.", Toast.LENGTH_LONG).show();
}
}
The pi variable is always null, so alarm starts ringing.
The next problem is, when I try to create PendingIntent with getBroadcast (instead of stack builder) my alarm never activates.
morningPendingIntent = PendingIntent.getBroadcast(this, AlarmPopUpDialog.REQUEST_CODE_MORNING, tmpIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Is using the stack builder the reason why i can't find the intent?
I feel stupid. My problem was that my AlarmPopUpDialog extended Activity not BroadcastReceiver class. When I added a class that extened BroadcastReceiver in the middle everything started to work.
morningPendingIntent = PendingIntent.getBroadcast(this, AlarmBrodcastReceiver.REQUEST_CODE_MORNING, tmpIntent, PendingIntent.FLAG_UPDATE_CURRENT);
and
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent(context, AlarmPopUpDialog.class );
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtras(intent);
context.startActivity(i);
}
}
I hope that this answer will help the next poor guy.
I have the following code for a one off alarm...
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(CalendarViewActivity.this, OneShotAlarm.class);
Bundle bun = new Bundle();
bun.putString("data", "hello this is my message...");
intent.putExtras(bun);
PendingIntent sender = PendingIntent.getBroadcast(CalendarViewActivity.this,
0, intent, 0);
// We want the alarm to go off 5 seconds from now. TODO
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5);
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
return false;
}
});
}
public class OneShotAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO
Toast.makeText(context, "Alarm! " + intent.getExtras().getString("data"), Toast.LENGTH_SHORT).show();
}
}
The alarm correctly goes off, but the "data" extra isn't getting retrieved for some reason, and is being set to null.
Thanks for the help!
Try:
Intent intent = new Intent(CalendarViewActivity.this, OneShotAlarm.class);
intent.putExtra("data", "hello this is my message...");
PendingIntent sender = PendingIntent.getBroadcast(CalendarViewActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Possible duplicate of getExtra from Intent launched from a pendingIntent
If that doesn't help, please tell us a bit more about your files (you need to have an activity where you set up the alarm, a broadcastreceiver that starts a service, and the service where you tell the app what to do when the alarm goes off)
Citation from the doc for putExtra function:
name The name of the extra data, with package prefix.
Couldn't it be the reason?