Search code examples
androidalarmmanager

AlarmManager onReceive constantly goes off


I've created a BroadcastReceiver with the following method :

public void SetAlarm(Context context, int repeatingHours)
{
    int repeatingTimeInMillis = 1000 * 60 * 60 * repeatingHours; // Millisec * Second * Minute * Hours where x is time between each alarm.      
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, AutoUpdateReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()* repeatingTimeInMillis, repeatingTimeInMillis, pi); 
    Toast.makeText(context, "Alarm set to repeat every " + repeatingHours + " hours", Toast.LENGTH_SHORT).show();
}

However as soon as I call SetAlarm it seems that onReceive constantly goes off.

This is where I call SetAlarm if that is in any way relevant :

receiver = new AutoUpdateReceiver();
        howOftenRadioGroup.setOnCheckedChangeListener(new android.widget.RadioGroup.OnCheckedChangeListener()
    {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId)
        {
            SharedPreferences prefEditor = getSherlockActivity().getSharedPreferences("com.kamstrup.ecamp", Context.MODE_PRIVATE);
            int repeatingHours = 0;
            switch(checkedId)
            {
            case R.id.auto_update_radio_hour_1:
                repeatingHours = 1;
                prefEditor.edit().putInt(SETTINGS_KEY, repeatingHours).commit();
                break;
            case R.id.auto_update_radio_hour_3:
                repeatingHours = 3;
                prefEditor.edit().putInt(SETTINGS_KEY, 3).commit();
                break;
            case R.id.auto_update_radio_hour_6:
                repeatingHours = 6;
                prefEditor.edit().putInt(SETTINGS_KEY, 6).commit();
                break;
            case R.id.auto_update_radio_hour_12:
                repeatingHours = 12;
                prefEditor.edit().putInt(SETTINGS_KEY, 12).commit();
                break;

            default:
                break;
            }
            receiver.SetAlarm(getSherlockActivity(), repeatingHours);
        }
    });

Why is this happening?


Solution

  • The issue I see is that you are using int as a type for repeatingTimeInMillis. You should always be using long type for timestamps. int's capacity is not enough, so you may have overflow turning your period in to a negative number.

    Also

    System.currentTimeMillis()* repeatingTimeInMillis
    

    definitely seems incorrect. You shold add time offset to current time, not multiply it.