I have a working alarm using the alarmManager class. If I set the alarm for any time before midnight of the current day everything is fine. If I want to set the alarm for the 7 a.m., however, and 7 a.m. has already come and gone for today, that of course does not work.
Is there a way to do this without implementing datepicker and dates into the program?
Below is a code sample. I can post more complete code if needed.
Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0);
repeatInterval = LoadPreferences("repeatInterval", repeatInterval); //gets number of minutes reminder should repeat
repeatIntervalMilliseconds = repeatInterval * 1000 * 60; //converts repeating interval to milliseconds for setRepeating method
//Set a one time alarm
if (repeatInterval == 0) {
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
AlarmReceiver alarmReceiver = new AlarmReceiver(this); //http://stackoverflow.com/questions/16678763/the-method-getapplicationcontext-is-undefined
Toast.makeText(AlarmActivity.this, "Your one time reminder is now set for " + hourSet + ":" + minuteSetString + amPmlabel, Toast
.LENGTH_LONG)
.show();
}
//Set a repeating alarm
else {
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), repeatIntervalMilliseconds, pendingIntent);
AlarmReceiver alarmReceiver = new AlarmReceiver(this); //http://stackoverflow.com/questions/16678763/the-method-getapplicationcontext-is-undefined
Toast.makeText(AlarmActivity.this, "Your reminder is now set for " + hourSet + ":" + minuteSetString + amPmlabel + " and will " +
"repeat " +
"every " +
repeatInterval + " minutes.", Toast.LENGTH_LONG).show();
}
I am testing this solution as recommended by Mike M. I will know tomorrow morning if this works. Mike if you want to post the same solution separately, and this is successful (and I think it will be), I can award you points.
//Add 1 day to alarmTime if alarmTime has already gone by for today
calendarComparison = now.compareTo(alarmTime);
if (calendarComparison == 1){
alarmTime.add(Calendar.DATE, 1);
}
Related
I'm trying to create periodical notifications.
So, I created a function to reschedule new notification time:
private void rescheduleNotification(Context context) {
long nextNotifTime = System.currentTimeMillis();
// Schedule next notification in 15 minutes
nextNotifTime += 15 * 60 * 1000;
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(nextNotifTime);
// It's an old version with the same result
//calendar.add(Calendar.MINUTE, 15);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss", Locale.ENGLISH);
this.logEvent(" Next notification time is: " + sdf.format(calendar.getTimeInMillis()));
Intent intent = new Intent(context, WordsBcReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager manager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 23) {
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextNotifTime, pendingIntent);
} else {
manager.set(AlarmManager.RTC_WAKEUP, nextNotifTime, pendingIntent);
}
this.logEvent(" Set next notification time: " + sdf.format(nextNotifTime));
}
Sometimes it runs correctly, but sometimes notification time shifts by exactly 12 hours.
I added special function to log all time manipulations, so the log contains:
29/12/17 11:30:36: Next notification time is: 29/12/17 12:00:36
29/12/17 11:30:36: Set next notification time: 29/12/17 12:00:36
seems OK, but adb shell dumpsys alarm says:
type=0 whenElapsed=+11h34m13s906ms when=2017-12-30 00:00:36
I tried to use Calendar (I to exclude some periods later), but result was the same.
Can't find the problem...
Hello friends that I developed an application Creating courses. I want to give notice when the time course.
So if you have classes Monday at 8 o'clock. 8 hours per week of class time came. I want to create a notification. I'm doing this with the alarmmanager and notification. I can give you one-time alarms. But somehow I could not repeat. Codes as follows. I will not try it because it is part of recevice.
private void alarmla() {
SQLiteDatabase db=activity.openOrCreateDatabase("SINIFD",activity.MODE_PRIVATE,null);
Cursor c = db.rawQuery("select * from ders", null);
if(c.getCount()>0){
c.moveToFirst();
do {
AlarmManager alarmManager = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
Toast.makeText(activity, c.getString(3).split(":")[0] + " " + c.getString(3).split(":")[1], Toast.LENGTH_LONG).show();
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
notificationIntent.putExtra("message", c.getString(1) + " dersi zamanı geldi. Kazanımlara ulaşmak için tıklayınız. İyi dersler.");
notificationIntent.putExtra("gizli", c.getString(6));
PendingIntent broadcast = PendingIntent.getBroadcast(activity, c.getInt(0), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar timeOff = Calendar.getInstance();
int days = Calendar.FRIDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)); // how many days until Sunday
timeOff.add(Calendar.DATE, days);
timeOff.set(Calendar.HOUR, Integer.parseInt(c.getString(3).split(":")[0])); //buraya 22 geliyor databaseden
timeOff.set(Calendar.MINUTE,Integer.parseInt(c.getString(3).split(":")[1])); //buraya 10 geliyor mesala
timeOff.set(Calendar.SECOND, 0);
timeOff.set(Calendar.MILLISECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(),AlarmManager.INTERVAL_DAY * 7, broadcast);
} while (c.moveToNext());
c.close();
}
db.close();
Toast.makeText(activity,"Vay be ayar ",Toast.LENGTH_LONG).show();
}
When there is no problem with the database of the adjustment.
Do not forget relaunch alarm manager after rebooting your mobile device!
Use broadcast receiver to catch this action
More about reboot : Trying to start a service on boot on Android
I have a service, which should start every hour. I am testing with a Note 3.
As this is Android KitKat I changed the code to:
AlarmManager am = (AlarmManager) this.getSystemService(ALARM_SERVICE);
int valueOfHour = 3600000;
long time = System.currentTimeMillis()+ (valueOfHour - (System.currentTimeMillis() % valueOfHour))+ 300000;
Log.i("Calculated Time:", time + " " + System.currentTimeMillis());
if(android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.KITKAT){
am.cancel(pintent);
am.setExact(AlarmManager.RTC_WAKEUP, time, pintent);
}
My problem is, that the Service is started at XX:05 (like I want it to) and also now and then at XX:34. I just don't know why. The calculated time is always right.
The code above is located in the onBind() Method.
I am using this code to launch an Alarm.
The alarm is set in an Activity that the user can launch.
//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);
Log.i("Test", "Current time: " + System.currentTimeMillis() );
Log.i("Test", "Calendar time: " + calendar.getTimeInMillis() );
int currentDate = calendar.get(Calendar.DATE);
calendar.set(Calendar.DATE, currentDate+1);
Log.i("Test", "Calendar time with a day added: " + calendar.getTimeInMillis() );
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);
I was told i need to supply a uniqu id so that the alarm doesnt over writte each other where getBroadcast() is.
The problem is how do I do this when the user can open the Activity as many times as they want?
Also if I supply a unique ID each time this means it could possibly set 5 of the same ALARMS because of the unique id's.
How or what is the best way to get around this?
you could always just use the unix timestamp of your target time as the unique id. that way, alarms for the exact time WILL override each other, while all other alarms will stay seperate
[EDIT:] Here is some example code:
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
Intent intent = new Intent(String.valueOf(calendar.getTimeInMillis()));
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);
I am using this code to set a Alarm everyday for 8 oclock the next day.
I am setting this alarm in an activity that can be opened based upon the user.
//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);
Log.i("Test", "Current time: " + System.currentTimeMillis() );
Log.i("Test", "Calendar time: " + calendar.getTimeInMillis() );
int currentDate = calendar.get(Calendar.DATE);
calendar.set(Calendar.DATE, currentDate+1);
Log.i("Test", "Calendar time with a day added: " + calendar.getTimeInMillis() );
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);
My only question is..Lets say at 10:00 o clock today am. i open the activity that alarm is set for tomorrow..Lets say i open the activity again at 12:00 am mid-night, will the alarm set earlier that day be overr written by the current alarm being set?
If you use the same request number (second parameter) while creating the PendingIntent object
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
then it will overwrite the current PendingIntent and hence will replace the current Alarm.
It will also depend on what you pass as the last parameter to it. Possible values given in the constants section here.