set repeated alarm manager for every hour in android - android

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)

Related

AlarmManager start Alarm Instantly

I have created a form where user specify date and time and adds alarm. I take these date and time and creates Alarm using AlarmManager.
The problem is that as soon as I click on CreateRemainder button, Alarm is fired
I am using following method to pass date, time values to AlarmManager class.
int year= Integer.parseInt(splitDate[0]);
int month= Integer.parseInt(splitDate[1]);
int day= Integer.parseInt(splitDate[2]);
int hour= Integer.parseInt(splitTime[0]);
int minute= Integer.parseInt(splitTime[1]);
int second= 0;
Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
cal.set(Calendar.DATE,day); //1-31
cal.set(Calendar.MONTH,month-1); //first month is 0!!! January is zero!!!
cal.set(Calendar.YEAR,year);//year...
cal.set(Calendar.HOUR_OF_DAY, hour); //HOUR
cal.set(Calendar.MINUTE, minute); //MIN
cal.set(Calendar.SECOND, second);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
I debug this and its getting the correct values, but it starts alarm immediately.
If i change the AlarmManager time to hard codded 10 seconds time, it starts remainder after 10 seconds.
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);
But if i add 10 Seconds to the Calender, it still start displaying alarm instantly after setting it.
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+10000, pendingIntent);
Usually, if the alarm is being fired as soon as you set it, it means that scheduled time is behind current time... So, AlarmManager fires it imediatelly
I suggest to add debug messages to debug. Something like:
Log.d("DEBUG", "Time from device: " + Calendar.getInstance().getTimeInMillis() + " Time passed to alarm: " + cal.getTimeInMillis());
Then, you can check Current Millis website and check if both times are correct.. Check if cal is really a future date
Also, if you want to add a time to calendar, use as follows Calendar.add() method:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
Use this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
}
If your alarm is getting called instantly than my guess is your cal's date is before today.

Alarm is ringing for all prevoius times using AlarmManager

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);

Set Repeating Alarm Every Day at Specific time In Android

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);
}

Alarm fires if the time is eariler than the current system time in android

I am using alarm manager to assign the alarm at specific time. I encountered a problem which is if I set the time earlier than the current system time, then the alarm action will be fired instantly. How to prevent this behavior ? Thanks
My code:
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent serviceIntent = new Intent(context,AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getService(context.getApplicationContext(), 234324243, serviceIntent, 0);
/*sample of setting eariler time
timeAlarm.set(Calendar.YEAR, 2013);
timeAlarm.set(Calendar.MONTH, 10);
timeAlarm.set(Calendar.DAY_OF_MONTH, 13);
timeAlarm.set(Calendar.HOUR_OF_DAY, 12);
timeAlarm.set(Calendar.MINUTE, 9);
timeAlarm.set(Calendar.SECOND, 0);
*/
alarmManager.set(AlarmManager.RTC_WAKEUP, timeAlarm.getTimeInMillis(), pendingIntent);
This is because the android alarm manager is designed by this.
You can modify your time if the time earlier than the current system time by 1 day or more.
like this:
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, second);
if (c.getTimeInMillis() < System.currentTimeMillis()){
c.add(Calendar.DAY_OF_MONTH, 1);
}

Repeat Alarm once in a week in android

I am trying to develop alarm functionality in a my app which runs on a week days specified by user on fixed time. Problem here is that my scheduler running for all days instead of running on specified day . here is the code i wrote for this please help to fix this
Calendar calNow = Calendar.getInstance();
SimpleDateFormat simpDate;
simpDate = new SimpleDateFormat("kk:mm:ss");
if(in_Date==1)
{
calNow.set(Calendar.HOUR_OF_DAY, hourOfDay);
calNow.set(Calendar.MINUTE, minute);
calNow.set(Calendar.SECOND, 0);
calNow.set(Calendar.MILLISECOND, 0);
}
else if(in_Date==2)
{
calNow.set(Calendar.HOUR_OF_DAY, hourOfDay);
calNow.set(Calendar.MINUTE, minute);
calNow.set(Calendar.SECOND, 0);
calNow.set(Calendar.MILLISECOND, 0);
calNow.set(Calendar.DAY_OF_WEEK,in_SelectedDay);
}
etTime.setText(simpDate.format(calNow.getTime()));
Seconds=calNow.getTimeInMillis();
private void setAlarm(){
//etTime.setText(simpDate.format(calNow.getTime()));
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
if(in_Date==1)
{
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Seconds,alarmManager.INTERVAL_DAY,pendingIntent);
}
else if(in_Date==2)
{
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Seconds,1 * 60 * 60 * 1000,pendingIntent);
}
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Seconds, AlarmManager.INTERVAL_DAY, pendingIntent);
In this line you set the start time to the user selected day, but then set the interval to INTERVAL_DAY.
You should use INTERVAL_DAY * 7 to make sure it repeats on a weekly basis instead:
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Seconds, AlarmManager.INTERVAL_DAY * 7, pendingIntent);
Is your alarm getting triggered everyday or every hour ?
I am supposing your in_Date is an indicator to choose daily alarm or for specific days .
My idea-> set the alarm for all days, check your day condition in the alarm receiver .

Categories

Resources