views:

940

answers:

2

Hello I have an android application which has a service running. After 20 mins from that service and other systems (such as GPS) starting I would like it to automaticly stop. I assume I need to use a Timer for that?

Can someone show an example of how I could do it?

+2  A: 

Maybe you don't even need a timer for that. Just keep track of when your service was started by storing System.currentTimeMillis() in a member variable and stopSelf your Service whenever you reach the timeout.

For example, include the following in your Service's busy part:

if(System.currentTimeMillis() - TIMEOUT > startTime) {
    stopSelf();
}
Josef
Thanks. Could you recommend the best place to locate this so it often run? The service in question is only a service controlling a WakeLock so its difficult to decide where to place it so the time-out will be constantly checked. Thanks.
Tom
If you really don't have a better place for it you can create your own Thread, use Timer.scheduleAtFixedRate, or the AlarmManager that was suggested in another answer.
Josef
+1  A: 

I would use AlarmManager. Set up a single-shot alarm to go off in 20 minutes. In the standalone BroadcastReceiver that receives the alarm, call stopService().

I have a blog post and some sample code in one of my books that cover AlarmManager, though they are all covering "the cron scenario", where you want to get control at boot time and set up a repeating alarm.

CommonsWare