animation123 animation123 - 6 months ago 19
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.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 7);
calendar.set(Calendar.MINUTE, 10);
calendar.set(Calendar.AM_PM,Calendar.AM);

Intent intent = new Intent(appContext, MyAlarmManager.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
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);
}


MyAlarmManager.java

public class MyAlarmManagerextends BroadcastReceiver {

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

setAlarm();

} }


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

Answer

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 
    calendar.add(Calendar.DATE,1);