Search code examples
androidtimeralarmmanageroncreate

alarm manager OnCreate() called randomly


I've tried to search around, but seems like I'm the only one who experiences such an error, so maybe someone would be able to point out what I did wrong.

I create an AlarmManager via this function:

public void startTimer() {
        Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);

        pendingIntent = PendingIntent.getService(MainActivity.this, 0,
                myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 10);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_FIFTEEN_MINUTES / 50, pendingIntent);

        Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG)
                .show();
    }

It is created as expected: OnCreate() is called then OnStart() is called. Then I stop the timer by calling the function:

private void stopTimer() {
        Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);

        pendingIntent = PendingIntent.getService(MainActivity.this, 0,
                myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
    }

And it is indeed stopped after this call.

The problem occurs afterwards, when AlarmManager's OnCreate() and OnStart() methods are called long after the app was closed with no easily seen system in those calls. Though it seems that this happens when my phone lacks free memory.

Any ideas? Thanks in advance!


Solution

  • Your service needs to call stopSelf() when it is done, or you need to switch to using an IntentService, which will automatically call stopSelf() when it is done. Right now, you are leaking the service, and Android is destroying and recreating it after a while.