I'am not a new Codename One user but this is my first time to use Local notification with this framework. In my app, i have a picker to allow the user to choose a time (hour and minutes). i recevied the time which is chosen with getTime() method. Now i want my local notification to trigger at that time. What is the correct value that i need to give at the second parameter of the Display.getInstance().scheduleLocalNotification() function?
So far what I have is this sample but I don't understand how to apply it to my needs:
Display.getInstance().scheduleLocalNotification(notification, System.currentTimeMillis() + 10 * 1000, LocalNotification.REPEAT_NONE);
From the Java doc of that method
#param firstTime time in milliseconds when to schedule the
notification #param repeat repeat one of the following: REPEAT_NONE,
REPEAT_FIFTEEN_MINUTES, REPEAT_HALF_HOUR, REPEAT_HOUR, REPEAT_DAY,
REPEAT_WEEK
So you can use your Date object method getTime() to return the time in millis for that date object.
EDIT
Let's assume this is the callback for your time picker
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Calendar date = Calendar.getInstance(); // This is the time now, so the day is set to today
date.set(Calendar.HOUR_OF_DAY, hourOfDay);
date.set(Calendar.MINUTE, minute);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.MILLISECOND, 0);
Display.scheduleLocalNotification(LocalNotification, date.getTime().getTime(), repeat);
}
Setting the second and millisecond is just to ensure the alarm goes off at the exact minute the user picked.
You can also change the day, month and year same as we changed the hour and minute.
Related
I am developing an app where I use an AlarmManager to schedule a time to open an Activity.
The chosen time is picked by a TimePicker.
Despite the time being the expected one when I call the method when.getTime , my activity doesn't open at the specified time.
Getting the time
int hour = tp.getCurrentHour();
int min = tp.getCurrentMinute();
MedicationReminder mr = new MedicationReminder(getApplicationContext());
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, hour);
c.set(Calendar.MINUTE, min);
if (hour > 12) {
c.add(Calendar.HOUR, 12);
}
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);
I tried replacing when.getTimeInMillis by 2000 and the activity opened , so the problem is not on my broadcast receiver.
Why is this happening?
Edit: I tried to schedule for the following minute and the acitivity opened.
I tried for the next 2 minutes and the activity opened with a delay of 12-15 seconds. Tried with 5 minutes and the activity didn't open
Try using setExact instead of set
...
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pi);
https://developer.android.com/training/scheduling/alarms
Condition :
User selects a active time period (from and to) for a day within which the alarm should be active with user specified interval.
User selects a inactive time period (from and to) for a day within which the alarm should be inactive or silent.
User selects the days on which the alarm should be fired.
eg: a user selects the active period of the alarm to be 9:00 am to 6:00pm with an interval of 20 minutes.
and he don't want the alarm to notify during his break time.say lunch break time is from 1:00 pm to 2:00 pm.He wasnts the alarm to be active only on Tuesday,Thursday and Sunday.
So during Tuesday, Thursday and Sunday ,the alarm should fire at 9:00am and fire with an interval of 20 minutes till 6:00pm. In between the alarm should be silent for 1:00pm to 2:00pm.
The user sets the timings in the main activity and the alarm for those timings is set in another activity where the alarm can be set and canceled.
Variables:
Active from time(in millisec) : int AFrom
Active to time (in millisec) : int ATo
Break from time (in millisec) : int BFrom
Break to time (in millisec) : int Bto
Alarm firing Interval (in millisec) : int interval
To select no: of days using a Android Alert Dialog with Multiple checkboxes:
String days[] = {"MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"} ;
Boolean checkedDays[] = {false,true,false,true,false,true,false};
final ArrayList DaysSelected = new ArrayList();
(this is just for information. Actual working Dialog box is created already. Just want to use the selected day's index for checking with the calendar day)
days[] is referenced with checkedDays[] to identify the selected days in setMultiChoiceItems().
Inside setMultiChioceItems():
builder.setMultiChoiceItems(days, checkedDays,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId,
boolean isSelected) {
if (isSelected) {
DaysSelected .add(selectedItemId);
} else if (DaysSelected .contains(selectedItemId)) {
DaysSelected .remove(Integer.valueOf(selectedItemId));
}
}
})
Alarm has to be set for the days whose checkedDays[] values are true
Note :All the variables all set static to use across all activities.
with the above variables how do I fire the below alarm for my above required condition?
Intent intent = new Intent(this,Notifier.class);
PendingIntent pendingIntent = PendingIntent.getActivitythis.getApplicationContext(),
12345, intent, FLAG_CANCEL_CURRENT );
AlarmManager am =(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, AT_from , interval, pendingIntent);
I would like to execute a piece of code every 24 Hours however I'm not sure how to do this.
I have some code that sets the time that I would like the cycle to start but not sure how to execute the end time
int startDay = 00; // 12am
int end = 24; // 12 pm
int hours = (end - startDay) % 24; //difference will be 24 hours
Calendar calInstanceOne = Calendar.getInstance();
// set calendar to 12 am
calInstanceOne.set(Calendar.HOUR_OF_DAY, startDay);
calInstanceOne.set(Calendar.MINUTE, 0);
calInstanceOne.set(Calendar.SECOND, 0);
calInstanceOne.set(Calendar.MILLISECOND, 0);
Do I create another Calendar instance, set to 12pm? and compare the two? Would really appreciate any insight into this.
I would like to execute a piece of code every 24 Hours
Use AlarmManager, in conjunction with either WakefulBroadcastReceiver or my WakefulIntentService. Ideally, use setInexactRepeating() on AlarmManager for INTERVAL_DAY, to allow Android to slide the actual time around to best save battery for the user.
You can use AlarmManager to make actions periodically:
Intent intent = new Intent(this, MyStartServiceReceiver.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, <24h in msecs>, pendingIntent);
Then you should register your BroadcastReceiver in the manifest and call the method you want to execute from this receiver.
First store your current time then whenever app will be open compare current time with previous store time if its greater or equal 24 hour
execute your code.
You may have several choices, let me outline the easiest one. The strategy is to simply use the system time to execute twenty four hours later:
package com.test;
import java.util.Calendar;
public class ExecuteCheck {
//Class fields
/* Number of milliseconds in a day
*
*/
private static final long C_DAY=24*60*60*1000;
//Object fields
/* Time last executed (or beginning of cycle), in milliseconds;
*
*/
private long lastExecuted = System.currentTimeMillis();
public ExecuteCheck() {
}
/** Set the current execution cycle time to now
*
*/
public void setExecutionTimeToNow() {
lastExecuted = System.currentTimeMillis();
}
/** Set the execution cycle time to be the value in the calendar argument.
* #param cal
*/
public void setExecutionTime(Calendar cal) {
lastExecuted = cal.getTimeInMillis();
}
/** Is it more than twenty-four hours since the last execution time?
* #return
*/
public boolean isTimeToExecute() {
return (System.currentTimeMillis() - lastExecuted) > C_DAY;
}
}
I am trying to schedule a service to run daily at a user specified time. I am using a timepicker to give the user control over what time of day the service is run.
Each time the user changes the time of day for the service to run I am updating the alarm manager.
Here is my code to do this:
void RescheduleOpeningRatesRetriever (string strTime)
{
var i = new Intent (this.ApplicationContext, typeof (OpenRatesService));
var src = PendingIntent.GetService (this.ApplicationContext, 0, i, PendingIntentFlags.UpdateCurrent);
var am = (AlarmManager)this.ApplicationContext.GetSystemService (Context.AlarmService);
var hour = TimePickerPreference.GetHour (strTime);
var minute = TimePickerPreference.GetMinute (strTime);
var cal = Java.Util.Calendar.GetInstance (Java.Util.TimeZone.Default);
cal.Set (Java.Util.CalendarField.HourOfDay, hour);
cal.Set (Java.Util.CalendarField.Minute, minute);
am.SetRepeating (AlarmType.RtcWakeup, cal.TimeInMillis, AlarmManager.IntervalDay, src);
}
I am not 100% sure if the code is scheduling the service to run properly as I have had mixed results from my tests.
The problem that I am experiencing now is each time I re-schedule the service to run with the above code, the service is started instantly.... I don't want to start the service until the configured time of day.
How can I schedule and update the service to run at a specified time of day without running the service instantly upon scheduling it with the alarm manager?
If the time for which you are setting the alarm is in the past then the alarm will goes off instantly. so first check whether the time is in past, if it is then set it for next day.
like::
Calendar rightNow = Calendar.getInstance()
if( cal.after( rightNow ) )
{
am.SetRepeating (AlarmType.RtcWakeup, cal.TimeInMillis, AlarmManager.IntervalDay, src);
}
else
{
cal.roll(Java.Util.CalendarField.DAY_OF_MONTH, 1);
SetRepeating (AlarmType.RtcWakeup, cal.TimeInMillis, AlarmManager.IntervalDay, src);
}
Okay, So I'm working on having an alarm that gives a notification at, lets say 3:00 PM daily, but I want this to be selectable by the user, between AM/PM, and Hours/Min freely changeable. I will probably use a TimePicker, and this is my code I have so far:
public void startAlarm() {
Intent intent = new Intent(currentDay.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(currentDay.this,0, intent,0);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 15*1000;
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,firstTime,AlarmManager.INTERVAL_DAY, sender);
}
So, I figure I'm going to be using something along the lines of:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 19);
cal.set(Calendar.MINUTE, 45);
and then using
cal.getTimeInMillis()
But this doesn't work, any ideas? Thanks!
EDIT: So, long story short, I know how to get the current time, then add lets say 15 seconds to it, but I want to have a definite time that WORKS for example 5:14 PM, and everything I've tried doesn't work
As far as I can tell you are getting a Calendar instance with the current date/time and then you are adding 19 hours and 45 minutes to it, NOT setting the time of the Calendar instance explicitly to 19:45. Is that what you are meaning to do? You need to use the Calendar set() method to set an explicit time.
From the API reference for Calendar
Calendar's getInstance method returns a calendar whose locale is based on system settings and whose time fields have been initialized with the current date and time:
Calendar rightNow = Calendar.getInstance()
public abstract void add (int field, int value)
Since: API Level 1
Adds the specified amount to a Calendar field.
Parameters
field the Calendar field to modify.
value the amount to add to the field.
Throws IllegalArgumentException if field is DST_OFFSET or ZONE_OFFSET.
EDIT: To convert local time to UTC...
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 19);
cal.set(Calendar.MINUTE, 45);
int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
firstTime = cal.getTimeInMillis() + offset;
NOTE: I haven't tried the above and there may be an easier way but it should work. It's hard for me to test stuff like this as my timezone is GMT/UTC.