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?