Search code examples
androidalarmmanager

Android AlarmManager Constantly goes off


I am using AlarmManager for my Timer. I have 2 classes.

In the first class (MainActivity) I am starting my alarm with the next code:

public void startAlarm(long Seconds) {
    Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);
    pendingIntent = PendingIntent.getService(MainActivity.this, 13141337,
            myIntent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, (int) Seconds);
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            pendingIntent);
}

In another class (AlarmSound), where the alarm goes off and the phone vibrates, I'm calling my cancel Alarm method.

public void stopAlarm(){
    Intent intentstop = new Intent(AlarmSound.this, MyAlarmService.class);
    PendingIntent senderstop = PendingIntent.getBroadcast(AlarmSound.this,
            13141337, intentstop, 0);
    AlarmManager myalarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    myalarm.cancel(senderstop);
    Log.w("Karl","stopAlarm?");
}

Is this the correct way to do this? Because my alarm constantly goes off on android 4.1.

Thanks in advance!


Solution

  • Your Cancel wont work. The pending Intents have to match - since they have a different context (MainActivity and AlarmSound) this cancel wont work. You have to also use getService on both. You can

    a) try to recreate a matching pending Intent

    b) get the pendingIntent that started the Service in the Service and use that to cancel

    But usually every Alarm just goes off once if you dont use setRepeating().

    Are you sure you are terminating your Service correctly with stopself() and are giving it the right flag in the onStartCommand() Method?