animation123 animation123 - 2 years ago 74
Android Question

Android alarmmanger gets called in different time?

I am working on Android AlarmManager and i found one issue in my code. The Alarm manager gets called in different time as well , i don't find what's the reason , i gave alarm at 7:10 AM but it gets called whenever i open the app in different time like 3:10 PM , 4:30 PM etc.

MyCode :

public void setAlarm(){

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 7);
calendar.set(Calendar.MINUTE, 10);

Intent intent = new Intent(appContext, MyAlarmManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(appContext, 0, intent, 0);

AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

public class MyAlarmManagerextends BroadcastReceiver {

public void onReceive(final Context context, Intent intent) {


} }

So , this is the above code , please let me know what's wrong in the code and suggest me some solution.

Answer Source

This is happening because the alarm is set in the past (when you set it anytime after 07:10 AM) So, you have to add 1 day if it is past 07:10 AM today.

Explanation -

Suppose it is 8 AM today and you are setting an alarm for 07:10, it sets an alarm for the same day 07:10 AM which is already past, hence it goes off whenever you open the app

Solution -

Option 1 - Either set date, month and year too like -

calendar.set(Calendar.DATE, date);
calendar.set(Calendar.MONTH, month);

Option 2 - Check what is the current time, if current time > the alarm time, add one day to the alarm

//If you are past 07:10 AM then 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download