Reputation: 749
I have following task: to make service which executes and gets data from Internet every 10 minutes. I try to use combination Service + Timer, but in this case I can't control service (I executes TimerTask with delay in onCreate() method of service, and when I interrupt service TimerTask won't stopped). I need 2 buttons only: "start service" and "stop service". What is the best way in this case? Thank you for helping.
Upvotes: 0
Views: 96
Reputation: 13801
You should use the AlarmManager. See this question Android: How to use AlarmManager for help on that. There is no need to waste a users memory by keeping your service alive doing nothing for 10 minutes. Also, if the phone is asleep, your timer will not run. By using the AlarmManager, the phone will automatically be woken up every 10 minutes and your service can be called to perform its internet download task.
Upvotes: 1
Reputation: 13690
If I understand you well, you want to know how to stop a TimerTask when you interrupt your Service?! If so, read on, otherwise please explain better.
To stop a TimerTask from executing again (assuming it was scheduled to run repeatedly) you must call the cancel() method. The preferred method is to let the TimerTask itself call the cancel() method after checking some boolean flag which can be set externally.
For example:
class MyTimerTask extends TimerTask() {
private boolean alive = true;
public void run() {
if (alive) {
// do something
} else {
cancel();
}
}
public void stop() {
alive = false;
}
}
Then, it's pretty obvious that when you interrupt your service, you just have to call MyTimerTask.stop().
Upvotes: 0