Tom
Tom

Reputation: 7426

Android Application and Timers

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?

Upvotes: 2

Views: 1592

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006664

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.

Upvotes: 1

Josef Pfleger
Josef Pfleger

Reputation: 74527

Maybe you don't even need a timer for that. Just keep track of when your service was started by storing [System.currentTimeMillis()](http://developer.android.com/reference/java/lang/System.html#currentTimeMillis() in a member variable and [stopSelf](http://developer.android.com/reference/android/app/Service.html#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();
}

Upvotes: 2

Related Questions