I am setting Alarm using Alarm Manager And setting this Alarm By Picking Values from SQlite Database.The Alarm is working fine for future Alarms but the problem is when I open the Activity in which Alarm Function is Called, The Alarm Start ringing for All Previous Times. How Should I solve this problem ?
Here is My Alarm Function
void Alaramset()
{
Cursor cursor=mydb.getAllData();
if (cursor.moveToFirst())
{
do{
String alarm1 = cursor.getString (cursor.getColumnIndex(DBHelper.ALARM_COLUMN_REMINDER1));
int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(DBHelper.ALARM_COLUMN_ID)));
int minute=Integer.parseInt (alarm1.substring(3, 5));
int hr=Integer.parseInt(alarm1.substring(0, 2));
Intent myIntent = new Intent(getActivity(), MyAlaramService.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent pendingIntent = PendingIntent.getService(getActivity(), id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
// Toast.makeText(getActivity(), ""+minute+" : "+hr, 300).show();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hr);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
while (cursor.moveToNext());
}
}
It looks like you are scheduling alarms that happen in the past.
Any alarm scheduled in the past will trigger immediately.
A simple solution would be to schedule past alarms for the next day.
Calendar now = Calendar.getInstance();
now.setTimeInMillis(System.currentTimeMillis());
if (calendar.before(now) {
// alarm has already happened. schedule it for tomorrow
calendar.add(Calendar.Date, 1);
}
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Related
I have an AlarmManager that I call at the end of every day, ie 23.59PM, to do some stuff for the new day. (Its called, NewDayReceiver.class.) It repeats every day.
I also set a broadcast receiver that will run the alarm on reboot. It all works fine.
However, if the phone is off at the end of the day, the alarm for that day is not called. When the phone is turned back on, on boot the alarm is set again, however its set for the end of the new day. It comes out, that the alarm for that day was never called. For example, if its off Sunday night, on Monday morning the phone is turned on but the alarm hasn't been called. It will only be called Monday night?
How can I do it, that on the boot broadcast receiver, I can check if the alarm was called for that day, and if it wasn't set the alarm to go off right away.
I hope its clear.
Here is my alarm for every day.
Intent intent = new Intent(this, NewDayReceiver.class);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
if(!calendar.before(Calendar.getInstance())) {
// Repeat every 24 hours
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent);
Log.d(TAG, "New day alarm set for:" + calendar.getTime() + " and will repeat every day");
}
Here is my BroadcastReceiver, that I call on boot:
public class BootBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "999.BootBroadcastReceiver";
#Override
public void onReceive(Context pContext, Intent intent) {
newDayAlarm(pContext);
newWeekAlarm(pContext);
}
private void newWeekAlarm(Context context) {
Intent intent = new Intent(context, NewWeekReceiver.class);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 55, intent, 0);
// real for end of week
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
if(!calendar.before(Calendar.getInstance())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Log.d(TAG, "New week alarm set for:" + calendar.getTime());
}
}
}
I want to set and cancel an Alarm for a particular time. I am doing the same using the TimePicker using the following code.
public void setRecurringAlarm(int randomTimer,long mills, int i){
Intent intent = new Intent(CreateAlarmActivity.this, AlarmReceiver.class);
intent.setData(Uri.parse("timer:" + i));
PendingIntent pendingIntent = PendingIntent.getBroadcast(CreateAlarmActivity.this, 1253, intent, PendingIntent.FLAG_CANCEL_CURRENT| Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,mills,
pendingIntent);
Toast.makeText(CreateAlarmActivity.this, "Alarm "+i+" isSet", Toast.LENGTH_LONG).show();
}
Note:-Suppose I set the alarm for 10:00 PM. It works fine for 10:00 PM. But when I again run the same code (after 10 PM) i.e once the time has been passed on which the alarm has been set and I recall that code (to reset the alarm), it starts running immediately. Why it is so ? I am unable to get where I am a wrong.
You can check if the alarm time is before the current time or not. If so, then set the alert time for the next day (if you want to fire alarm at least once, or want to set Repeating alarm).
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
if (System.currentTimeMillis() > cal.getTimeInMillis()) {
calendar.add(Calendar.DATE, 1);
}
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
public void scheduleAlarm() {
// time at which alarm will be scheduled here alarm is scheduled at 1
// day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
// Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, 20);
cal.add(Calendar.MINUTE, 00);
cal.add(Calendar.SECOND, 00);
Intent intent = new Intent(CreateAlarmActivity.this, AlarmReceiver.class);
// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
PendingIntent.getBroadcast(this, 1, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled ", Toast.LENGTH_LONG)
.show();
}
Hope this will help you
2 things:
If you are "recalling that code" by calling setRecurringAlarm(randomTimer, mills, i) using the same value for the mills parameter, then the time for the alarm will be in the past and it will trigger immediately (if you schedule an alarm with a trigger time in the past, the alarm triggers immediately).
Please remove | Intent.FILL_IN_DATA from the call to PendingIntent.getBroadcast(). It doesn't belong there as this parameter should contain only PendingIntent flags and it may do some damage.
I am using Alarm manager to run alarm at specific time every day. Below is the code
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 00);
calendar.set(Calendar.MINUTE, 00);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, OnAlarmReceive.class);
PendingIntent pendingIntent =PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
24*60*60*1000, pendingIntent);
I am Setting alarm at 12AM every day. And Below is the code for BroadCastReciever
#Override
public void onReceive(Context context, Intent intent)
{
System.out.println("Time is 12 Am");
Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}
Problem in this code is Alarm is Triggered As soon as i Run the Application Irrespective of time. Any help will be Appreciated. Thank You
The alarm will only fire immediately if you set the alarm in the past.
E.g. it is now 10:00h and you want to set an alarm every day at 09:00. To avoid this, you have to look what time it is now, and shift the alarm 1 day if that is the case... This allows you to use the setRepeating method (which is more precise than setInexactRepeating)
This fixes the issue:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 00);
calendar.set(Calendar.MINUTE, 00);
if(Calendar.getInstance().after(calendar)){
// Move to tomorrow
calendar.add(Calendar.DATE, 1);
}
//... continue like before by setting the alarm
I had the same issue as you and I couldn't get it to work. Plus all the examples I could find were also setting a specific date, not only just a time. This should work for you:
Intent myIntent = new Intent(ThisActivity.this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager) Context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(ThisActivity.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent); //Repeat every 24 hours
Hope this helps you fix your problem!
try to use this:
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, intent);
You could use something like this:
Calendar cal = Calendar.getInstance();
if(cal.getTimeInMillis() < System.currentTimeMillis()) {
cal.add(Calendar.DAY_OF_YEAR, 7);
}
Newbie here, I have this function setAlarm:
public void setAlarm(){
SharedPreferences sa=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int hr=sa.getInt("alarmhour", 6);
int mn=sa.getInt("alarmminute", 0);
String st1=sa.getString("alarmstatus", "Alarm Disabled");
if(st1.equals("Alarm Enabled"))
{
AlarmManager ala = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent inte = new Intent(this, epicalarm.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, inte, 0);
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, hr);
time.set(Calendar.MINUTE, mn);
time.set(Calendar.SECOND, 0);
ala.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);
}
}
Each time I call the function setAlarm , the onReceive method gets called and displays the alarm . Why?
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, h);
calendar.set(Calendar.MINUTE, m);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND,0);
// if values of h and m are less than current time
//then 'if' block will executes and adds the amount of days as 1 to your calendar object.
if (calendar.before(Calendar.getInstance()))
{
calendar.add(Calendar.DATE, 1);
}
//you will get an alarm` after a day instead of now
ala.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
The second parameter in
ala.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);
is to specify when to trigger the alarm first. In your code, you are triggering it for the time you read from your shared preferences. If that time has already elapsed, the alarm gets triggered immediately. That may be one reason why the onReceive() method gets called.
Check if the time you read is some time in the future.
I want to fetch location every hours in android . For that i use alarm manager and set repeated alarm for every hour and just want to write into file after fix time i.e at 8 AM and 12 PM .
I got a problem in setting alarm manager , while i set for every one hour but it execute in 1/2 hour .
on button click i start service :
serviceButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(AutoMainActivity.this, TrackerService.class);
pendingIntent = PendingIntent.getService(AutoMainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, ALARM_TRIGGER_AT_TIME,
3600000, pendingIntent);
//3600000 1hrs
finish();
}
});
And Service Class are as :
Tracker Service.class
String FINAL_STRING;
SharedPreferences pref;
static final int START_TIME = 8;
static final int MID_TIME = 12;
java.util.Date systemDates = Calendar.getInstance().getTime();
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if(hour == START_TIME)
{
edit.putString("smsdata", FINAL_STRING);
edit.commit();
//sendSms(START_TAG+pref.getString("smsdata", ""));
edit.putString("smsdata", "");
edit.commit();
}else {
System.out.println("currentdate:"+simpleDateFormat.toString());
System.out.println("current_time:"+currentTime);
Editor edit = pref.edit();
edit.putString("smsdata", pref.getString("smsdata", "")+FINAL_STRING+"#");
edit.commit();
if(hour==MID_TIME)
{
//sendSms(START_TAG+pref.getString("smsdata", ""));
generateNoteOnSD("\n"+START_TAG+pref.getString("smsdata", ""));
edit.putString("smsdata", "");
edit.commit();
System.out.println("mid time");
}
}
When i execute this the service start on every 30min. but i want on every 60min.
First, you really want to use one of the available constants, like INTERVAL_HOUR, with setInexactRepeating().
Second, setInexactRepeating() is inexact. Android reserves the right to flex the times of the alarms to coalesce events with other scheduled inexact alarms.
So, try switching briefly to setRepeating(). If it now works as you expect, your behavior is due to the "inexact" nature of setInexactRepeating().
Also, you can use adb shell dumpsys alarm to examine the scheduled alarms. It may be that you have two alarms scheduled, each going off once per hour.
setInexactRepeating() is the reason why it is not working as you expected. Try following:
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, firstStart, interval, pendingIntent );
In my application I have the functionality to trigger an alarm in 4 scenarios:
Only once for a user-chosen date and time
Daily for the chosen time
Weekly according to chosen date and time
User chosen custom days of the week
I successfully implement the first 3 scenarios by using the following:
Only once:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, Integer.parseInt(date[0]));
calendar.set(Calendar.MONTH, (Integer.parseInt(date[1])) - 1);
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date[2]));
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
For daily scheduling:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
calendar.set(Calendar.SECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
For weekly scheduling (as per system date):
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
calendar.set(Calendar.SECOND, 0);
//long interval = calendar.getTimeInMillis() + 604800000L;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);
How do I implement weekly alarm scheduling for custom days of the week?
private void scheduleAlarm(int dayOfWeek) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
// Check we aren't setting it in the past which would trigger it to fire instantly
if(calendar.getTimeInMillis() < System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_YEAR, 7);
}
// Set this to whatever you were planning to do at the given time
PendingIntent yourIntent;
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, yourIntent);
}
private void setUpAlarms() {
scheduleAlarm(Calendar.MONDAY);
scheduleAlarm(Calendar.FRIDAY);
}
Attribution
Source: https://microeducate.tech/repeating-alarm-for-specific-days-of-week-android/ ,
Question Author : Dhruvil Patel(https://stackoverflow.com/users/1367157/dhruvil-patel) , Answer Author : MBH(https://stackoverflow.com/users/2296787/mbh)