I am trying to use this to set an alarm that goes off everyday.
String alarm = Context.ALARM_SERVICE;
Calendar calendar = Calendar.getInstance();
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
Intent intent = new Intent("NEW_ITEM");
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
calendar.setTimeInMillis(System.currentTimeMillis());
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1*AlarmManager.INTERVAL_DAY, sender);
Without running it, the code looks good to me... Obviously, if you set this alarm every time you start the activity, the alarm will go off immediately since: am.setRepeating(AlarmManager.RTC_WAKEUP, **calendar.getTimeInMillis()**, 1*AlarmManager.INTERVAL_DAY, sender); Tells the alarm manager to alert right now (2nd param) and to repeat in a day (3rd param, assuming your constant is correct).
If you want the alert to start only in 24 hours, simply change the line to:
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, sender);
Code looks good, but you have to be aware of one thing. If the user decides to set the alarm again (for example, by hitting the 'set the alarm' button) the old one will be replaced. If you want to avoid this, check out this topic: Using Alarmmanager to start a service at specific time
Related
I want to trigger a daily alarm in my application. I can see the alarm being triggered daily at the correct time for 2 or 3 days but it does not trigger after that. For example if I set alarm to trigger at 08:00 AM, it will trigger at 8 AM daily for 2 or 3 days and after that there is no alarm triggered. There is no app crashing or anything, it simply does not trigger. I have a BroadcastReceiver registered (in AndroidManifest.xml) for this alarm and i can see logs being printed daily at the correct time but only for 2 or 3 days. After that there is no activity and the app just seems to die down.
Please find my code below :
final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final long intervalDay = 60*60*24*1000L;
final long alarmTime = calendar.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, intervalDay, pendingIntent);
I have also used alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, AlarmManager.INTERVAL_DAY, pendingIntent); but it did not make any difference (didnt expect it to make any though).
I do not want to use alarmManager.setInexactRepeating() as it does not trigger the alarm at exact time but there is slight delay.
Any help appreciated !!
Thanks.
That's because android cannot hold the alarm content for more than 2-3 days. Though there is no sure shot solution that i know.
I fixed it by cancelling and resetting alarm everytime alarm is triggered.
Something like this.
Instead of using setRepeat use set or setExact to trigger for once:
if(android.os.Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT) {
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmtime, pendingIntent);
} else {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmtime, pendingIntent);
}
Then in onRecieve() method of your alarmReciever after performing your task, reset the alarm again for next followed by cancelling all pending intents:
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), reminderModal.get_remindID(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
Hope it helps.
I created a service that will check some online data in specific time of the day and everyday (for example at 6 AM), and rather than using a background running service and broadcast receiver I decided to use AlarmMananger and the code below:
Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
My questions are:
1- How to unregister from the AlarmManager when user decided to de-activate my service?
2- What is the use of this line
calendar.setTimeInMillis(System.currentTimeMillis());
3- What could happen if I called the same function above with the same params and data, will AlarmMananger overwrite my request or it will register a new one, and when the time comes (6 AM) it will call my service twice?
4- Is it possible to check AlarmMananger if it has successfully registered my Intent?
Edit 1:
The code below is not triggering my broadcast receiver, why?
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 6); // For 6 AM
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
PendingIntent pi = PendingIntent.getService(this, 0, new Intent(this, mybroadcastreceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
AndroidManifest.xml
<receiver
android:name=".mybroadcastreceiver"
android:enabled="true"
android:exported="true"></receiver>
Coming to all your questions :-
How to unregister from the AlarmManager when user decided to de-activate my service?
Answer :- To cancel an AlarmService you created, you need to cancel it like this.
this.getAlarmManager().cancel(pendingIntent);
where this is the service (or Activity/Context) from where you called the AlarmService.
What is the use of this line
calendar.setTimeInMillis(System.currentTimeMillis());
Well if you are aware of the method Date.setTime(), which generates the Date object with milliseconds provided in the argument. Calender.setTimeInMillis() does the same for the Calender object. System.currentTimeMillis() is used to provide the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. ( I guess you are aware of whole Timestamp concept)
3. What could happen if I called the same function above with the same params and data, will AlarmMananger overwrite my request or it will register a new one, and when the time comes (6 AM) it will call my service twice?
As the documentation says, If there is already an alarm scheduled for the same IntentSender, that previous alarm will first be canceled.
4. Is it possible to check AlarmMananger if it has successfully registered my Intent?
I think it is possible, but there is no such method to check it directly, you need to do the hack. I think you will find this answer suitable.
I hope this helps you :)
You can use if else function for register and unregister from AlarmManager.
for example checkBox isSelectted() or not.
calendar.setTimeInMillis(System.currentTimeMillis());
this line will return you system time in millisecond format. This format is like this "2547889955511"
yes if you can perfectly set up AlarmManager your pending intent can call your service twice.
yes you have to set up perfectly then it will possible to check AlarmMananger is it successfully registered your Intent or not.
I need to the Android app to send notification to remind users at 8am, 3pm and 8pm every day. So I use the following three lines in onCreate() of the MainActivity, when the application starts. However, when I run the app, all three notification are coming at once instead of at the wanted time.
setRepeatedNotification(1,8,0,0);
setRepeatedNotification(2,15,0,0);
setRepeatedNotification(3,20,0,0);
Why is that? I also attach the setRepeatedNotification function here. Thank you!
private void setRepeatedNotification(int ID, int hh, int mm, int ss) {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, ID, alarmIntent, 0);
Calendar calendar = Calendar.getInstance();
// calendar.set();
calendar.set(Calendar.HOUR_OF_DAY, hh);
calendar.set(Calendar.MINUTE, mm);
calendar.set(Calendar.SECOND, ss);
// Clear previous everyday pending intent if exists.
if (null != mEverydayPendingIntent) {
alarmManager.cancel(mEverydayPendingIntent);
}
mEverydayPendingIntent = pendingIntent;
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mEverydayPendingIntent);
}
Here is the updated code:
private void setRepeatedNotification(int ID, int hh, int mm, int ss) {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(StartActivity.this, AlarmReceiver.class);
alarmIntent.putExtra("ID",ID);
Log.d("setRepeatedNotification", "ID:" + ID);
PendingIntent pendingIntent = PendingIntent.getBroadcast(StartActivity.this, ID, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hh);
calendar.set(Calendar.MINUTE, mm);
calendar.set(Calendar.SECOND, ss);
//check whether the time is earlier than current time. If so, set it to tomorrow. Otherwise, all alarms for earlier time will fire
if(calendar.before(now)){
calendar.add(Calendar.DATE, 1);
}
mEverydayPendingIntent = pendingIntent;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mEverydayPendingIntent);
}
I see two potential problems with your setup with AlarmManager. The first arises when the device goes to sleep.
From AlarmManager's documentation:
If an alarm is delayed (by system sleep, for example, for non _WAKEUP alarm types), a skipped repeat will be delivered as soon as possible. After that, future alarms will be delivered according to the original schedule; they do not drift over time. For example, if you have set a recurring alarm for the top of every hour but the phone was asleep from 7:45 until 8:45, an alarm will be sent as soon as the phone awakens, then the next alarm will be sent at 9:00.
As you can see, if you've set an alarm and the device has gone to sleep, without using AlarmManager.RTC_WAKEUP there could be a long delay depending on how long the device has been in sleep for. If you've never touched your device and no other alarms caused a wakeup, it could cause all your alarms to stack up upon the next hour that the device is awake for.
Another potential issue I see is that you are retrieving a Calendar instance representing the time right now, but then setting the hour, minute and second by yourself. The current day and the current year have been automatically populated from the current time.
Again, from the documentation (emphasis mine):
If the stated trigger time is in the past, the alarm will be triggered immediately, with an alarm count depending on how far in the past the trigger time is relative to the repeat interval.
In this case, if your method was invoked past 8 pm on the given day, calendar.getTimeInMillis() will return a timestamp in the past for all three alarms, causing them to be triggered immediately since 8 am, 3 pm and 8 pm have already past in that day. In this case, you must first evaluate whether the current time is past the alarm interval you are trying to set and add 1 day more onto the time you are setting to make sure the alarm has been set in the future.
I am starting my service using below code repeatedly. My service starts at 8am everyday. And AlarmManager repeates at every 1 min. I want to stop this sevice at 6pm. how can I do this ?
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent loggerIntent = PendingIntent.getBroadcast(this, 0,new Intent(this,AlarmReceiver.class), 0);
Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.HOUR_OF_DAY, 08);
timeOff9.set(Calendar.MINUTE, 00);
timeOff9.set(Calendar.SECOND, 00);
//--------------------------------------------------------------------------------------------------------------------
long duration = userinterval * 60 * 1000;
manager.setRepeating(AlarmManager.RTC_WAKEUP,timeOff9.getTimeInMillis(), duration, loggerIntent);
In order to cancel at 6pm exactly, I would consider 2 options:
Each time the alarm triggers (i.e. every 1 minute), check the time, and cancel if time is after 6PM.
Set a once-off alarm in AlarmManager to go off at 6PM exactly. In that alarm, cancel.
I prefer option 2 for simplicity, and modularity of each code block. So for me, I would use (2) in my proof-of-concept code, while working on the solution.
But option 1 is better from a resources point of view, as the Android system only needs to remember a single alarm. I would use (1) in my final production code.
This way of working is just my personal preference, and most ppl probably will say to use (1) right away from the start.
The details about cancelling are below...
As for how to cancel an alarm, you don't often beat an answer by #commonsware....
Below answer copied from How to cancel this repeating alarm?
Call cancel() on AlarmManager with an equivalent PendingIntent to the one you used with setRepeating():
Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this,
0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
In my application i want to use alarm service for specific period of time.I'm taking start time and end time values from user and saving it in database,Now i want to start a alarm service at start time and alarm should go off at end time specified by user.I'm new to this topic and not able to understand how to implement this...Any help will be appreciated.Thank u..
This is how you implement an alarm manager. But you will need to read about Calendar object in android also.
String alarm = Context.ALARM_SERVICE;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);//Just an example setting the alarm for the 8th hour of a day.
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND, 0);
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
//This is the intent that is launched when the alarm goes off.
Intent intent = new Intent("WAKE_UP");
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
//If the user wants the alarm to repeat then use AlarmManager.setRepeating if they just want it one time use AlarmManager.set().
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);
}
Also you will need to register a BroadCast Receiver to except the intent when the alarm sets it off.
You create the BroadCast reciever and register it in your manifest to receive the intent from the alarm.
http://www.vogella.de/articles/AndroidServices/article.html
Here is a great tutorial to help you understand better
The key is to use the AlarmManager with a pending intent.
mAlarmSender = PendingIntent.getService(AlarmService.this,
0, new Intent(AlarmService.this, AlarmService_Service.class), 0);
Then you create the AlarmManager from the current context:
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
And schedule the previously created pending intent.
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 30*1000, mAlarmSender);
On schedule the AlarmService_Service service will be called, or you can put another intent like open a specific activity.
Here is the complete example of how you can schedule an alarm: AlarmService.java