I've got a problem with the AlarmManager. I'm able to set up the Alarm with this code
private void setAlarm(long when) {
Intent intent = new Intent(NoteActivity.this, AlarmReceiver.class);
intent.putExtra("ID", note.getId());
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, PendingIntent.getBroadcast(NoteActivity.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(getApplicationContext(),"Reminder set up", Toast.LENGTH_SHORT).show();
}
This code works well if I set long when = 5 * 1000; \\For example 5secs later, but if I use this code
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
long selectedDate = date.getTime();
long timeSince1970 = System.currentTimeMillis();
long timeForAlarm = selectedDate - timeSince1970;
Intent intent = new Intent(NoteActivity.this, AlarmReceiver.class);
intent.putExtra("ID", note.getId());
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeForAlarm, PendingIntent.getBroadcast(NoteActivity.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(getApplicationContext(),"Reminder set for "+calendar.getTime().toString(), Toast.LENGTH_SHORT).show();
my alarm triggerd 2secs later. What I'm doing wrong? :/
I've tried AlarmManager.ELAPSED_REALTIME_WAKEUP and AlarmManager.RTC_WAKEUP but nothing changed.
Please do not check my question as duplicated. I didn't find something to try that solved my problem.
Assuming that you are working in Android Studio (if not - you must switch), click F1 while your text pointer is on set method and read description of AlarmManager::set.
Note: Beginning in API 19, the trigger time passed to this method is
treated as inexact: the alarm will not be delivered before this time,
but may be deferred and delivered some time later. The OS will use
this policy in order to "batch" alarms together across the entire
system, minimizing the number of times the device needs to "wake up"
and minimizing battery use. In general, alarms scheduled in the near
future will not be deferred as long as alarms scheduled far in the
future.
Instead of set use setExact
manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeForAlarm, PendingIntent.getBroadcast(NoteActivity.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Related
I want to repeat a notification in android at a scheduled time in a specific day of the week (8:30am Saturday). I have set up the code and the alarm works (with the notification). The alarm need not wake up the device and fires the notification on next wake up.
Problem: The alarm is fired once every time the app is newly opened.
Tried different combinations but cant get it to work. Your help is much appreciated. Thank you.
MainActivity.java (OnCreate)
AndroidHelper ahelper= new AndroidHelper();
public static long rand_news_notify_freq= AlarmManager.INTERVAL_DAY * 7;
Calendar ca = Calendar.getInstance();
ca.set(Calendar.HOUR_OF_DAY,8);
ca.set(Calendar.MINUTE,30);
ca.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
ca.set(Calendar.SECOND, 0);
ca.set(Calendar.MILLISECOND, 0);
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
ahelper.setAlarms(alarmMgr, getApplicationContext(), RandomNewsNotification.class, ca, rand_news_notify_freq);
AndroidHelper.class
public class AndroidHelper{
public AndroidHelper()
{
}
public void setAlarms(AlarmManager alarmMgr, Context tctx, Class alarmClass, Calendar calendar, long freq)
{
Intent alarmIntent = new Intent(tctx, alarmClass);
PendingIntent pendingIntent = PendingIntent.getBroadcast(tctx, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//alarmMgr.setRepeating(alarmMgr.RTC, calendar.getTimeInMillis(), freq, pendingIntent); // This is not working
alarmMgr.setInexactRepeating(alarmMgr.RTC, calendar.getTimeInMillis(), freq, pendingIntent); // This is not working too (same problem)
}
}
What needs to be changed?
I don't know you want to set exact repeating or inexact repeating. for exact repeating, you yourself should handle repeating with exact methods and don't use repeating methods of alaramManager like setInexactRepeating.
also consider if device is on Doze mode, alaram won't fire. so you should use setExactAndAllowWhileIdle method to guarantee that the alarms will execute.
you can see more detail on Android Developer document:
https://developer.android.com/training/scheduling/alarms
Explanation:
I have calendar in which i set the events on the particular day of the given month.The event is stored into the database. on the event day is occurs it is trigger an alarm to notice the user.
suppose, my event is save on the 29/05/2016 then my alarm is triggered on the particular date.
Notice:i have multiple event created on the particular month.e.g. on the 29th may or 30th may also.
MyQuestion is how can i fire the multiple alarm on the particular multiple days.
Please, understand the flow what i exactly want?
If you want to play alarm for particular date and time , following code may help you
Calendar cal=Calendar.getInstance();
cal.set(Calendar.MONTH,5);
cal.set(Calendar.YEAR,2012);
cal.set(Calendar.DAY_OF_MONTH,11);
cal.set(Calendar.HOUR_OF_DAY,16);
cal.set(Calendar.MINUTE,10);
cal.set(Calendar.SECOND,0);
Intent _myIntent = new Intent(getApplicationContext(), ReceiverClass.class);
PendingIntent _myPendingIntent =
PendingIntent.getBroadcast(getApplicationContext(), 123, _myIntent,
PendingIntent.FLAG_UPDATE_CURRENT| Intent.FILL_IN_DATA);
AlarmManager myAlarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//myAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), _myPendingIntent);
myAlarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), _myPendingIntent);
calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,date.getYear());
calendar.set(Calendar.MONTH,date.getMonth()+1);
calendar.set(Calendar.DAY_OF_MONTH,date.getDate());
calendar.set(Calendar.HOUR_OF_DAY,time.getHours());
calendar.set(Calendar.MINUTE,time.getMinutes());
calendar.set(Calendar.SECOND,time.getSeconds());
Intent myIntent = new Intent(context, AlarmReciever.class);
myIntent.putExtra("ReminderDetails",reminderDetails);
myIntent.putExtra("requestCode", requestCode);
pendingIntent = PendingIntent.getBroadcast(context, (int) (requestCode), myIntent,0);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, date.getTime(),
interval, pendingIntent);
The following code here is good live for setting a calender time at the specified time and date.
And the most important thing here stands is that what do you pass in 2nd argument in alarmManager.setInexactRepeating(_) method,which is
date.getTime(), which is the only thing will work instead of using
calendar.getTimeinMillis() method, because that will return some unexpected time to be launched for intents.
I have following piece of code which should be trigger alarm after 2 days. However It gets triggered after every 2 hours, some users says they get it after every 5 mins too.
settingDB.updateSetting("Notification",1);
Calendar Calendar_Object = Calendar.getInstance();
Calendar_Object.set(Calendar.HOUR_OF_DAY, 10);
Calendar_Object.set(Calendar.MINUTE,01);
Calendar_Object.set(Calendar.SECOND, 0);
//Calendar_Object.set(Calendar.DAY_OF_WEEK, 1);
// MyView is my current Activity, and AlarmReceiver is the
// BoradCastReceiver
Intent myIntent = new Intent(Setting.this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Setting.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
//Log.w("alarm set for " , Calendar_Object.getTime().toString ());
/*
* The following sets the Alarm in the specific time by getting the long
* value of the alarm date time which is in calendar object by calling
* the getTimeInMillis(). Since Alarm supports only long value , we're
* using this method.
* 3*1000*24*3600
*/
//alarmManager.setRepeating(AlarmManager.RTC, Calendar_Object.getTimeInMillis(),3600*1000**24,pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC, Calendar_Object.getTimeInMillis(), 86400000*2, pendingIntent);
Could you please help me to resolve the problem?
The calendar object passed to alarm manager is set to a fixed time. This will cause the alarm to go off when that time comes.
you could also do this
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()
+ 60*1000,timeofAlarm pendingIntent);
The calendar object you passed seems to do the damage. Follow my example above , once the alarm will go off after like a min. Just to check if the alarm is working,(you may want to add anytime there ,its upto you).
Realtime is useful(and perhaps recommended) if you want your alarm to go off every given time, irrespective of user time state
I am setting alarms at diffrent time . I want to delete a particulat alarm.
Ex. I set 100 alarms at diiferents times , now I want to Delete an alarm set at 25 Feb 2012 10.45 AM. How Can I do that.
I written following code to set alarm.
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
GregorianCalendar gc=new GregorianCalendar();
gc.set(2012, 1, 22, 10, 42,0);
Intent intent = new Intent(this, AlarmService.class);
gc.set(Calendar.AM_PM,0);
final PendingIntent sender = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, gc.getTimeInMillis(), sender);
I have a broadcast receiver to recieve the alarm.
You need to save the request code of alarm,that is 1 in your case here. The 2nd parameter you pass in your PendingIntent.getBroadcast() method is your request code for a particular alarm.So when you save request code along with the time for what you set alarm,it would be easy for you to get the particular alarm instance and then you can cancel it using:
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, OneShotAlarm.class); //OneShotAlarm is the broadcast receiver you use for alarm
PendingIntent sender = PendingIntent.getBroadcast(context,alarm_request_code, intent, 0);
am.cancel(sender);
You should take care that each of your request code for different alarms should be unique,otherwise your alarm will be rescheduled with new time you set with the older request code.
Hope you get the point.
You might need to store it in some form of data structure to keep track of the time and the object. That being said, I have not tried storing AlarmManager objects before.
I am currently trying to write alarm manager that will make an alarm go off within a specified period of time, daily. First I check to see if the user has had an alarm set for that for that day:
if ((User.getReminderTime(Home.this) > 0)
&& (dt.getDate() != today.getDate() || dt.getDay() != today
.getDay())) {
AppointmentManager.setFutureAppointmentCheck(this
.getApplicationContext());
User.setLongSetting(this, "futureappts", today.getTime());
}
Then I go and set the actual alarm to go off between 12 and 12:10 of the next day:
public static void setFutureAppointmentCheck(Context con) {
AlarmManager am = (AlarmManager) con
.getSystemService(Context.ALARM_SERVICE);
Date futureDate = new Date(new Date().getTime() + 86400000);
Random generator = new Random();
futureDate.setHours(0);
futureDate.setMinutes(generator.nextInt(10));
futureDate.setSeconds(0);
Intent intent = new Intent(con, FutureAppointmentReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(con, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, futureDate.getTime(), sender);
}
Now I setup a test environment for this to go off every two minutes and it seems to be working fine, however when I deploy to an actual device, the reciever does not seem to be recieving the alarms. I thought it might be an issue with the device being asleep, so I added the power manager. But it still does not work:
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "keepAlive");
wl.acquire();
setFutureAppointments(context.getApplicationContext());
AppointmentManager.setFutureAppointmentCheck(context
.getApplicationContext());
User.setLongSetting(context.getApplicationContext(), "futureappts",
new Date().getTime());
wl.release();
Anyone see anything I am doing blatantly wrong or am I going about this incorrectly? thanks for any and all help.
I usually do something more along the lines of:
Intent i = new Intent(this, MyService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pi); // cancel any existing alarms
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, pi);
This way, you don't have to worry about re-setting the AlarmManager in your Service.
I usually run this bit of code when my app starts (onResume in my main activity) and in a BroadcastReceiver that is set up to receive BOOT_COMPLETED.
I've written a guide on creating Services and using the AlarmManager, which is based on my own experience and a few tips & tricks I picked off from watching a Google I/O talk. If you're interested, you can read it here.
To answer your question below, all I can do is quote the docs:
public void setInexactRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)
Schedule a repeating alarm that has inexact trigger time requirements; for example, an alarm that repeats every hour, but not necessarily at the top of every hour. These alarms are more power-efficient than the strict recurrences supplied by setRepeating(int, long, long, PendingIntent), since the system can adjust alarms' phase to cause them to fire simultaneously, avoiding waking the device from sleep more than necessary.
Your alarm's first trigger will not be before the requested time, but it might not occur for almost a full interval after that time. In addition, while the overall period of the repeating alarm will be as requested, the time between any two successive firings of the alarm may vary. If your application demands very low jitter, use setRepeating(int, long, long, PendingIntent) instead.
In conclusion, it's not very clear. The docs only say that the alarm "may vary". However, it should be important for you to know that the first trigger might not occur for almost a full interval after that time.
This is working, this will shoot alarm after every 5 seconds
private void setRecurringAlarm() {
Logger.d(IConstants.DEBUGTAG, "Setting Recurring Alarm");
Calendar updateTime = Calendar.getInstance();
updateTime.set(Calendar.SECOND, 5);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent recurringDownload = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.cancel(recurringDownload);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), 1000 * 5, recurringDownload); //will run it after every 5 seconds.
}