4

I want to use Alarm Manager in order to execute repeating task while my app is launched, but I have a problem with cancelling the task.

That's my code:

Service:

public class SyncService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("#####", "It's alive!");
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Application:

public class TerminalApplication extends Application {
    PendingIntent pintent;
    AlarmManager alarm;

    @Override
    public void onCreate() {
        super.onCreate();
        Intent intent = new Intent(this, SyncService.class);
        pintent = PendingIntent.getService(this, 0, intent, 0);
        alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Log.e("#####", "Starting alarm");
        alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), 5 * 1000, pintent);
    }

    @Override
    public void onTerminate() {
        clear();
        super.onTerminate();
    }

    public void clear() {
        alarm.cancel(pintent);
        Log.e("#####", "Alarm cancelled");
    }
}

And that's what I see in logs:

07-09 14:53:30.399: ERROR/#####(1743): Starting alarm
07-09 14:53:52.690: ERROR/#####(1590): It's alive!
07-09 14:54:02.690: ERROR/#####(1590): It's alive!
07-09 14:54:12.690: ERROR/#####(1590): It's alive!
07-09 14:54:20.475: ERROR/#####(1743): Alarm cancelled
07-09 14:54:22.695: ERROR/#####(1590): It's alive!
07-09 14:54:32.696: ERROR/#####(1590): It's alive!

I'm using same intent for cancelling the task, even the same instance, but it doesn't work. Can you help me?

uncle Lem
  • 4,954
  • 8
  • 33
  • 53

1 Answers1

0

curious does pintent is still holding the details of SyncService in clear()?

user755
  • 2,521
  • 3
  • 18
  • 29
  • yep, pintent remains absolutely same – uncle Lem Jul 10 '13 at 11:47
  • 1
    I have used RTC_WAKEUP flag which fits with my requirement and setrepeating and cancel are working as expected. try changing this one and verify if it fits with your functionality as the API say " This alarm does not wake the device up; if it goes off while the device is asleep, it will not be delivered until the next time the device wakes up. " – user755 Jul 10 '13 at 14:46
  • Sorry, couldn't check earlier. That's a little bit weird, but it works. Unfortunately, I still don't understand, why my code didn't worked, but thanks you anyway. – uncle Lem Jul 15 '13 at 10:37