Search code examples
androidbroadcastreceiveralarmmanager

Broadcastreceiver triggered at Start


I set clock alarm for midnight. But setting the Alarm triggers my Broadcast receiver? I set the Alarm at the App start. the code:

    //set the alarm
    protected void onCreate(Bundle savedInstanceState) {
            as=new AlarmSetter();
            as.SetAlarma(this); .........

    //the AlarmSetter
    public class AlarmSetter  {

        public void SetAlarma(Context context){

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM); 

         Intent intent = new Intent(context, AlarmKicked.class);
         PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1333333, intent, PendingIntent.FLAG_UPDATE_CURRENT);
         AlarmManager am =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
         am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,
                 pendingIntent);
        }

    }


    //and my Broadcast reciever 
    public class AlarmKicked extends BroadcastReceiver{



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

            NotificationsA.Notizer(context);

            System.out.println("IT IS MIDNIGHT! SETTING TIMER..");

        }

    }

//Manifest
<receiver android:name=".AlarmKicked" android:process=":remote"/>

When I start the App, I set the Allarm.. but in the same time I get in the Logcat : IT IS MIDNIGHT! SETTING TIMER.. What is triggering my Broadcastreciever at the Start?

EDIT:

Works!:

public void SetAlarma(Context context){

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.HOUR, 0);
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.AM_PM, Calendar.AM); 

Solution

  • You are setting for midnight, however your Calendar's time is now midnight of the present day, which has already passed.

    This causes the Alarm to go off as soon as it's registered.

    Quoting from the documenatiation:

    If the time occurs in the past, the alarm will be triggered immediately, with an alarm count depending on how far in the past the trigger time is relative to the repeat interval.

    Instead, add a day to your calendar, that should stop it from going off.

    Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.HOUR, 0);
            calendar.set(Calendar.AM_PM, Calendar.AM); 
            calendar.add(Calendar.DATE, 1);