Starting alarm service in android - android

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

Related

Broadcast receiver fires late than it should be

I am trying to fire a receiver at specific time of day which is 12 Am, but sometimes it fires at 1 or 2 AM.
I added a notifcation to my service to know when exactly the receiver start accourding to the alarm, and I find out, it start at 1, or 2 even 3 Am, not as I adjusted.
calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
Intent intent = new Intent(getActivity(), PrefAlarm.class);
long firstMillis = System.currentTimeMillis();
alarm = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);
pIntent = PendingIntent.getBroadcast(getActivity(), PrefAlarm.REQUEST_CODE2,intent ,PendingIntent.FLAG_CANCEL_CURRENT);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis( ),AlarmManager.INTERVAL_DAY,pIntent);
If you use setInexactRepeating(), the time that it triggers is inexact. This means that Android can adjust the trigger time to save battery (usually by delaying the trigger until the device is awake). Read the documentation about AlarmManager and JobScheduler and about how to get thedesired behaviour for your application.

How to get my service started periodically at specific time of the day

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.

AlarmManager keeps screen of my device on

I have one problem I need to set AlarmReceiver.
I am using this code for it:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 5);
AlarmManager alarm = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(getActivity(), AlarmReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(getActivity(), 0, i, 0);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*5, pIntent);
So it means that this AlarmManager will call AlarmReceiver every 5 seconds, but problem is that if I don't turn my screen OFF manually, screen will stay ON and this is not what I want.
From the AlarmManager reference documents:
The parameter AlarmManager.RTC_WAKEUP, will wake up the device (in case of device sleep) to deliver the Alarm. You may use AlarmManager.RTC but that won't be wake up the device and your Alarm won't be delivered until next time device wakes up.
A better option would be to use a Service for this purpose, as they are designed to carry out the background tasks.

Stop a service at specific time

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);

AlarmManager not setting, Alerting everytime activity is opened

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

Categories

Resources