Alarms before alarm time - android

Please help me guys Im creating an alarm clock project and i have a problem.
This is the problem i need to set an alarm before the current time like if the time now is 1:00pm ill set 10:00am so basically it has 18 hours remaining and 59 minutes before alarm time, the problem is once you set an alarm like 10:00am on 1:00pm time it will alarm just after you click ok
if (setHour < c.get(Calendar.HOUR_OF_DAY)
|| setHour == c.get(Calendar.HOUR_OF_DAY)
&& setMinute < c.get(Calendar.MINUTE)) {
c.set(Calendar.HOUR_OF_DAY, setHour);
c.set(Calendar.MINUTE, setMinute);
c.set(Calendar.SECOND, 0);
client.setAlarmNotification(c, requestCode);
}
setHour is from timepicker as well as setMinute. Requestcode is unique as it comes from id from database (PrimaryKey) so no problem with that, it all works when you alarm after the current time but NOT before the current time . Guys please help me im dealing with this for couple of days now. thank you in advance
-raphaelle

As I understand you just need to set alarm for next day.
Calendar c = Calendar.getInstance();
if (setHour < c.get(Calendar.HOUR_OF_DAY)
|| setHour == c.get(Calendar.HOUR_OF_DAY)
&& setMinute < c.get(Calendar.MINUTE))
{
c.set(Calendar.HOUR_OF_DAY, setHour);
c.set(Calendar.MINUTE, setMinute);
c.set(Calendar.SECOND, 0);
long time = c.getTimeInMillis();
time = time + 1000*60*60*24; // Add 24h to the date
c.setTimeInMillis(time);
client.setAlarmNotification(c, requestCode);
}

Set the calendar to the time AND date you wish to use instead of only setting the time.
Calendar c= Calendar.getInstance();
c.set(year,month,day,hour,minute);
client.setAlarmNotification(c, requestCode);
Note: Months are 0 to 11 NOT 1 to 12
If you just want to fire the alarm tomorrow, then add a day to the calender like this:
c.add(Calendar.DATE,1); // Add one day to the calendar
Then you need only set the time.

Related

Calendar not returning the correct time

I want to pick a time from time picker and set an alarm using AlarmManager for that time.
When I use when.getTimeInMillis the value returned is different from the time I´ve set.
For example , if I set the time at 20:40 and I print the value of when.getTime I get 17:12 from next day.
Why is this happening?
Getting time from time picker
MedicationReminder mr=new MedicationReminder(getApplicationContext());
int hour = tp.getCurrentHour();
int min = tp.getCurrentMinute();
Calendar c=Calendar.getInstance();
c.add(Calendar.HOUR, hour);
c.add(Calendar.MINUTE, min);
mr.setReminder(new Medication(name,quant_aux,time),c);
Setting alarm
Intent i = new Intent(mContext, MedicationReceiver.class);
i.putExtra("medName",medication.getName());
i.putExtra("medQuant",medication.getQuantity());
PendingIntent pi=PendingIntent.getBroadcast(mContext,0,i,0);
mAlarmManager.set(AlarmManager.RTC_WAKEUP,when.getTimeInMillis(),pi);
Instead of
Calendar c=Calendar.getInstance();
c.add(Calendar.HOUR, hour);
c.add(Calendar.MINUTE, min);
Try doing
Calendar c=Calendar.getInstance();
c.set(Calendar.HOUR, hour);
c.set(Calendar.MINUTE, min);
If you want to use 24h hour format, then use
c.set(Calendar.HOUR_OF_DAY, hour);
I'm not 100% that's the problem since you didn't include all the code, but I think you're adding 20 hours to the current time instead of setting the calendar to hour 20.
Another note: I believe getCurrentHour() and getCurrentMinute() have been deprecated since API 23, so I suggest you use getHour() and getMinute() instead.

Accessing hour,minute and second using Calendar class

I am trying to set an alarm on a particular day and time.So setting hour and minute using Calendar.But when i try to access the hour which is set in Calendar using cal.set,i get a different value than that was set by me manually.
Code
Calendar cal=Calendar.getInstance();
cal.set(Calendar.HOUR,7);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Toast.makeText(getApplicationContext(), "Alarm worked. "+cal.HOUR+cal.MINUTE,cal.SECOND Toast.LENGTH_LONG).show();
Result i want
Alarm worked. 7:30:0
What i get now
Alarm worked. 10:12:13
P.S
1.I found many posts which deal with Calendar issues but couldn't find my solution.
2.The result what i am getting i.e 10:12:13 is not my current time(current date,current minute,current second) either.So i don't know why and from where these data are coming.
3.I tried using HOUR_OF_DAY instead of HOUR but nothing useful.
Solution
Toast.makeText(getApplicationContext(), "Alarm worked. "+cal.get(Calendar.HOUR)+" "+cal.get(Calendar.MINUTE)+" "+cal.get(Calendar.SECOND), Toast.LENGTH_LONG).show();
This worked because Calendar.HOUR,Calendar.MINUTE are constants.See the answer of #PopoFibo to get the clear picture.
The problem is in your Toast, you are printing the constants of the Calendar class:
Calendar.HOUR = 10
Calendar.MINUTE = 12
Calendar.SECOND = 13
Instead, get the value at their respective indexes - like for HOUR it would be cal.get(Calendar.HOUR)
System.out.println(cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));
Would give (correct output):
7:30:0
And, System.out.println(Calendar.HOUR + ":" + Calendar.MINUTE + ":" + Calendar.SECOND);
Would give (incorrect output):
10:12:13
Date s = cal.getTime();SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a");String t = sdf.format(s);
Toast.makeText(this, t, Toast.LENGTH_SHORT).show(); for more ref. see http://www.asbhtechsolutions.com/android-tutorial/1-android-get-current-time-and-date
can you try with:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 7);
calendar.set(Calendar.MINUTE, 30);
and then toast it
add these lines before setting time..
Cal.set(Calendar.MONTH , month);
Cal.set(Calendar.YEAR, year);
Cal.set(Calendar.DAY_OF_MONTH,day);

Scheduling a task for certain days of the week in Android

As the title implies, I'm looking to schedule a task to run on certain days at certain times. For example, I might have it run at 5:00 every Tuesday and Thursday. I've seen several scheduling methods for Android, but all of them seem to operate in the form of "do task after n delay" or "do task every n seconds".
Now I could probably jury-rig it by having it calculate the time to the next execution during the execution of the task itself, but that seems inelegant. Is there some better way to do this?
You've to set an Alarm to perform those tasks. Most probably you will end up calling a Service once the alarm is triggered:
private void setAlarmToCheckUpdates() {
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.HOUR_OF_DAY)<22){
calendar.set(Calendar.HOUR_OF_DAY, 22);
} else {
calendar.add(Calendar.DAY_OF_YEAR, 1);//tomorrow
calendar.set(Calendar.HOUR_OF_DAY, 22); //22.00
}
Intent myIntent = new Intent(this.getApplicationContext(), ReceiverCheckUpdates.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)this.getApplicationContext().getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
However, if you need to set specifically a day:
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
if (weekday!=Calendar.THURSDAY){//if we're not in thursday
//we calculate how many days till thursday
//days = The limit of the week (its saturday) minus the actual day of the week, plus how many days till desired day (5: sunday, mon, tue, wed, thur). Modulus of it.
int days = (Calendar.SATURDAY - weekday + 5) % 7;
calendar.add(Calendar.DAY_OF_YEAR, days);
}
//now we just set hour to 22.00 and done.
Above code is a little bit tricky and mathematic. If you wan't something stupid aswell as easy:
//dayOfWeekToSet is a constant from the Calendar class
//c is the calendar instance
public static void SetToNextDayOfWeek(int dayOfWeekToSet, Calendar c){
int currentDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
//add 1 day to the current day until we get to the day we want
while(currentDayOfWeek != dayOfWeekToSet){
c.add(Calendar.DAY_OF_WEEK, 1);
currentDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
}
}

Activity and a Service in same android application

I am developing an application in which user would first be presented a simple UI with days and timings. user would select timings against each day. and click a button "Done". Now this would start alarm services to trigger on every day as per selected timings. (and will turn the bluetooth device off/on those timings). right now i am using separate service for each day (beginner's instinct). The application is working fine. Now what i want is that when the user click on the "Done" button, the application should keep running in background and when the user again click the application icon and click on the "Default" button, it should stop all the services. How can i achieve that ? Code for triggering service every sunday is as follows
time interval of 7 x days for the alarm to repeat every 7 days
long interval = 1000 * 60 * 60 * 24 * 7; // to make the alarm repeat at every 7 days
//getting values for hours, mins and AM/PM from the spinner boxes for sunday
index = sunHr.getSelectedItemPosition();
int sunHrInt = Integer.parseInt(hrList[index]);
index = spinnerSunMin.getSelectedItemPosition();
int sunMinInt = Integer.parseInt(minList[index]);
index = spinnerSunAmPm.getSelectedItemPosition();
//conversion of time to 24 hrs format
if (ampmList[index] == "AM") //(convert to 24 hr format)
{
if (sunHrInt == 12)
{
sunHrInt = 0;
}
else
{
if (sunHrInt != 12)
sunHrInt = sunHrInt + 12;
}
}
//setting current calender
Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar
//setting calender for sunday
Calendar calSun = new GregorianCalendar();
calSun.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
calSun.set(Calendar.HOUR_OF_DAY, sunHrInt);
calSun.set(Calendar.MINUTE,sunMinInt);
calSun.set(Calendar.SECOND, 0);
calSun.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
calSun.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
calSun.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
//finding out when the sunday is to occur from today
days = 8 - calSun.get(Calendar.DAY_OF_WEEK); // how many days until Sunday
if (days >= 7)
{
days = days - 7;
}
calSun.add(Calendar.DATE, days);
//finally triggering the intent
Intent myIntentSun = new Intent(AndroidAlarmService.this, SunOffAlarmService.class);
pendingIntentSun = PendingIntent.getService(AndroidAlarmService.this, 0, myIntentSun, 0);
AlarmManager alarmManagerSun = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManagerSun.set(AlarmManager.RTC_WAKEUP, calSun.getTimeInMillis(), pendingIntentSun);
Use Preferences to store values and try it. it may help you

AlarmManager launching multiple times

I am using this code to create an Alarm in a activity that can be launched by the user.
The Alarm sends an intent that launches a broadcast reciever and then a service.
private void setGameAlerts(){
//Setting alarm to fire off NEW_GAME intent every 24 hours.
String alarm = Context.ALARM_SERVICE;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND, 0);
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
Intent intent = new Intent("NEW_ITEM");
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);
Log.e("RELEASE LIST", "ALARM Set For 1 day from " + calendar.getTimeInMillis());
For some reason EVERYTIME the activity is launched it Automatically sends this intent and the service is launched. is there something wrong with my code that is causing this to happen other than the alarm going off everyday at 8 oclock?
It looks to me like you're setting it for 8am TODAY, not 8am tomorrow. For example, if I run this code:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND, 0);
Log.i("Test", "Current time: " + System.currentTimeMillis() );
Log.i("Test", "Calendar time: " + calendar.getTimeInMillis() );
calendar.add(Calendar.DATE, 1);
Log.i("Test", "Calendar time with a day added: " + calendar.getTimeInMillis() );
I get the result:
10-06 23:26:50.050: INFO/Test(8890): Current time: 1317968810056
10-06 23:26:50.050: INFO/Test(8890): Calendar time: 1317913200000
10-06 23:26:50.050: INFO/Test(8890): Calendar time with a day added: 1317999600000
The calendar time is a number less than the current time, so therefore that calendar entry is in the past. It might make some sense that Android would immediately send the intent for an event that has past. If you add a day to it, or specify a date in your Calendar object, it should work.
Note that this numerical dates are simply the standard Unix time with milliseconds added on. If you drop the last three digits and put the number into a Unix time converter, you'll be able to check that the numbers you're working with make sense. Eg: use 1317999600 with the Unix time converter and you'll get 10am EST, which is 8am PST (my time zone).
I hope that helps!

Categories

Resources