0

MainActivity.java

Intent intent = new Intent(this, AlarmReceiver24.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,1);
calendar.set(Calendar.MINUTE, 50);
calendar.set(Calendar.SECOND, 0);
String time= String.valueOf(calendar.getTime());
Log.i("Time:",time);
//repeat alarm every 24hours
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, alarmIntent);

AlarmReceiver class

public class AlarmReceiver24 extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
        reference.child("Total").setValue(0);
        Toast.makeText(context, "Total Reset", Toast.LENGTH_SHORT).show();

    }
}

Android Manifest

<receiver android:name=".AlarmReceiver24"/>

I want the code to run at midnight 12:00:00 once everyday but it keeps firing again and again even after using AlarmManager.INTERVAL_DAY. I don't know what I'm doing wrong.

2 Answers2

2

Each time you opens MainActivity it creates a new PendingIntent

When you start MainActivity you should remove all previously scheduled alarms.

Also

calendar.set(Calendar.HOUR_OF_DAY, 1);
calendar.set(Calendar.MINUTE, 50);
calendar.set(Calendar.SECOND, 0);

is not midnight.

calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

is midnight

Henry Twist
  • 5,666
  • 3
  • 19
  • 44
anatoli
  • 1,663
  • 1
  • 17
  • 43
  • if i cancel the pending intent then it is not calling the alarm at all where do i need to specific the cancel() method – Krishna Pal Mar 29 '21 at 20:38
  • creating of Alarm each time you opens it is a bed solution. check [this](https://stackoverflow.com/questions/4556670/how-to-check-if-alarmmanager-already-has-an-alarm-set) one. – anatoli Mar 30 '21 at 18:08
0

The Alarm was getting set in past so added this condition and it was solved

if(calendar.before(Calendar.getInstance()))
            calendar.add(Calendar.DATE,1);