Search code examples
androidnotificationsalarm

Android notification sent on start


I have set up an alarm manager to go off at noon everyday and send a notification, and is working perfectly except for one part. When I open the app for the first time it immediately sends out a notification, regardless of the time.

Intent myIntent = new Intent(arg0, NotificationService.class);
    myIntent.putExtra("compDate", tti.getEvents()[0][1]);
    AlarmManager alarmManager = (AlarmManager)arg0.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getService(arg0, 0, myIntent, 0);

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

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

That method is being called by this piece of code in the onCreate method

int f = preferences.getInt("numberOfLaunches", 1);

    if(f < 2){
        alarmMethod();
        f++;
        editor.putInt("numberOfLaunches", f);
        editor.apply();
    }

That is the only time when it is being called


Solution

  • Most likely caused by this:

    If the stated trigger time is in the past, the alarm will be triggered immediately

    http://developer.android.com/reference/android/app/AlarmManager.html#setRepeating

    Make sure you set your first alarm to be in the future.