my alarm manager calendar comparison is not getting the expected result - android

I made a comparison between two calendars:
Year, Month and day are the current year, month and day: but the result is not as expected if the time of the first calendar is after the current time the calendar waits till that time and starts ringing but if it's before the current time the calendar starts ringing directly so it's always accessing the second condition:
public void scheduleAlarm()
{
//to initialize the time variable not a real value:
Long time=Long.parseLong("0");
int hour=calendar.get(Calendar.HOUR);
int minute=calendar.get(Calendar.MINUTE);
Calendar cal_now = new GregorianCalendar(Year,Month,Day, hour, minute,Calendar.SECOND);
Calendar cal_alarm_first=new GregorianCalendar(Year,Month,Day,21,14,0);
//if the first calendar is in the past increment its day by one:
if(cal_alarm_first.before(cal_now)){
Notif_Body=getResources().getString(R.string.remembrance_body_first);
//here if the first alarm is already gone I should add a day and it should ring after a day from now with the specified hour and minute...
cal_alarm_first.add(Calendar.DATE, 1);
time=cal_alarm_first.getTimeInMillis();
}
else if(cal_alarm_first.after(cal_now)){
//the problem is here it always access this condition even if the first calendar time is before the current time for example same date but the first calendar is 9:14 and current time is 9:17 it always access this condition and the alarm starts ringing...
Notif_Body=getResources().getString(R.string.remembrance_body_first);
time=cal_alarm_first.getTimeInMillis();
}
//to send this alarm to be retrieved by the broadcast receiver class:
Intent intentAlarm = new Intent(this, TimeAlarm.class);
//add the notification body to the intent:
intentAlarm.putExtra("Notif_body", Notif_Body);
// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
I really can't figure out what the problem is!! thanks.
Edit:
so the cause of this unexpected result was because of the 24hours format I am adding the time of the first calendar in 24hours format and the current time is getting its time placed as 12 hours format so need to get both of them in 24 hours format;
Edit2:
So I changed the
int hour=calendar.get(Calendar.HOUR);//12 hours
to
int hour=calendar.get(Calendar.HOUROFDAY);//24 hours
and basically worked will add it as an answer if it really worked...

the cause of this unexpected result was because of the 24hours format I am adding the time of the first calendar in 24hours format and the current time is getting its time placed as 12 hours format so need to get both of them in 24 hours format;
So I changed the:
int hour=calendar.get(Calendar.HOUR);//12 hours
to
int hour=calendar.get(Calendar.HOUROFDAY);//24 hours
and it worked!!

Related

How to send a notification on specific dates by checking the date

I have an application which I want to send notifications in odd days (like 1,3,5 days of month). After research, I understood that I need a service. But I can't figure out how to get the new date every day, or how to notice the service that the day has changed... Something like a listener on day changed... I searched a lot, and only found references on how to schedule a notification at a certain date, but that's not what I need, as I want to verify date every day. Thank you very much for any help !
You can do this with the help of Android Alarms.
The steps that you need to do :
Start an Alarm for the date and time at which you need to show the notification.
Subscribe for Reboot Broadcast receiver and set the same alarm again (since the alarm that you set will be gone once the device is restarted)
Once the alarm is ticked, you can show the notification from the Alarm Broadcast receiver and then set for the new alarm.
To schedule an ALarm :
AlarmManager mgr=
(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(ctxt, ScheduledService.class);
PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + DIFF_PERIOD, PERIOD, pi);
Where PERIOD : 48hours in millisecond
DIFF_PERIOD : time to your nearest tick. That is if you are in day 2 and you need to trigger the alarm in day 3, then this value will be : 24hrs in millisecond
To answer your comment.
To find the day of the month, you can use the follwing :
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);

Figure out the time in millis for alarm

I am making a simple alarm clock application that mimics the default alarm app that comes with Android Lollipop.
The set*( ) methods of an AlarmManager require the date on which the alarm should be fired as a Unix epoch.
The UI is rather simple with a TimePicker.
So, given the current time and the time the user has selected from TimePicker, how do I figure out the time in milliseconds when the alarm should be fired?
Update:
There are two cases I run into:
Selecting the time that is after the current time:
Assume it is 11am and the user selects the time from the time picker as 03pm. In this case, I know that the alarm should be scheduled for the same day.
Selecting the time that is before the current time:
Assume it is 11am and the user selects the time from the time picker as 10am. In this case, I know that the alarm should be scheduled for the next day's 10am.
Ok here you go:
// Get the current time
final Date currentTime = new Date();
// Set the hours and minutes from the time picker against todays date
final Calendar selectedTime = Calendar.getInstance();
selectedTime.set(Calendar.HOUR_OF_DAY, hourFromTimePicker);
selectedTime.set(Calendar.MINUTE, minuteFromTimePicker);
// If the current date is greater than the hour and minute from time picker add one day
if (currentTime.getTime() > selectedTime.getTime().getTime()) {
selectedTime.add(Calendar.DAY_OF_YEAR, 1);
}
// Schedule the alarm
//AlarmManager.set(selectedTime.getTime().getTime());
if you store data in java Date object:
long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.just subtract.
Another way if you look only at time within day:
int ms = 1000*SECONDS + 1000*60*MINUTES + 1000*60*60*HOURS
I would use a android.text.format.Time class
call the setters on the Time class to set the Hour, Minute, Second, etc. The Hours are in 24H time, so if the current hour > selected hour then you know to increment days by 1
Finally, call Time#toMillis(boolean ignoreDst) to get the system time in millis, and pass that to AlarmManager
EDIT: GregorianCalendar should be used instead.

android best way to set an alarm in android

i have a general question to set an alarm in android.
at the moment, the user can chose a date and time with a date picker (which is a date in the future).
then i will set the the delay time for the alarm.
I convert the chosen date & time in milliseconds and subtract System.currentTimeMillis() = this difference I set for the delay of my alarm.
my question is, if this the best way to calculate the delay or is there a better solution?
this calculation i use for update an alarm, too
Look at the Android Alarm Manager class. You can use it to set alarms at specific times, without calculating the delay.
final AlarmManager am = (AlarmManager) App.instance.getSystemService(Context.ALARM_SERVICE);
Calendar c = GregorianCalendar.getInstance();
c.set(2015, 12, 20, 10, 30);
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), operation);
where operation is a PendingIntent of the action you want to do when the alarm triggers.
My solution for you here:
You should convert normal datetime to timestemp formart
You can calculate by subtract future timestemp (which is set by alarm time) with current timestemp of phone to get return value then convert it to hour, munite and day number.
If after calculate get result is zezo then you notify alarm to user.
else nothing to do

PopUp Alarm on selected days and selected time in android

I want to popup an alarm on selected day i.e. Monday ,Tuesday and so on. And at selected time on every week. I've an idea about interval but I don't know how to get the next day and popup alarm ?
You need to use the AlarmManager and get a WakeClock while processing the Intent in Service (make sure to release it and chose the right kind).
Here is a great example :
https://stackoverflow.com/a/8801990/220710
To get the day current day of the week, look at this question :
Android: how to get the current day of the week (Monday, etc...) in the user's language?
Then you would use :
setInexactRepeating(int type, long triggerAtMillis, long intervalMillis, 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.
Then you would need to set :
type = RTC_WAKEUP
intervalMillis = ms in a week
triggerAtMillis = System.currentTimeMillis() + ms to the next Monday, Tuesday or
whatever
intent = the intent you want to fire to a Service that
will process it.

Android Calendar has always the same date

i want an alarm to go off when user checks in a checkbox. Here is my code:
if (cb1.isChecked())
{
Calendar calA = Calendar.getInstance();
//calA.set(Calendar.YEAR, Calendar.YEAR);
//calA.set(Calendar.MONTH, Calendar.MONTH);
//calA.set(Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH);
calA.set(Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY);
calA.set(Calendar.MINUTE, Calendar.MINUTE);
calA.set(Calendar.SECOND, Calendar.SECOND);
calA.set(Calendar.MILLISECOND, Calendar.MILLISECOND);
alarmManager.set(AlarmManager.RTC_WAKEUP, calA.getTimeInMillis(), pendingIntentA);
Toast.makeText(main.this, "Set time: " + String.valueOf(calA.getTime()), Toast.LENGTH_SHORT).show();
}
Other codes are working fine, and if i set the hour and minute to specific ones, like
calA.set(Calendar.HOUR_OF_DAY, 15);
calA.set(Calendar.MINUTE, 24);
it's working, but with this code i always get this toast message:
Sat Mar 05 11:12:00 or Sat Mar 05 11:12:13
(neither the date nor the time is good)
What is wrong with my code?
Calendar.HOUR_OF_DAY is a constant, which just so happens to be an integer.
When you
calA.set(Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY);
you are in fact setting the hour of day to whatever number happens to have been chosen for this constant. This value has no real meaning in relation to the hour of day, so it'll produce a garbage result.
When you get the calendar, it's by default set to the current time, so if that's what you're going for, simply don't set the time:
Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time:
Calendar rightNow = Calendar.getInstance();
If you then want to set a time like "5 minutes into the future", do something like:
calA.add(Calendar.MINUTE, 5);
If you still get an incorrect time, verify that the system time is set correctly.
Source:
Calendar documentation
Calendar calA = Calendar.getInstance(); returns a calendar object whose locale is based on system settings and whose time fields have been initialized with the current date and time.
Sebastian P is right that Calendar.HOUR_OF_DAY is a constant, a key/index used for referencing the actual hour value.
See http://developer.android.com/reference/java/util/Calendar.html

Categories

Resources