I am running a Service
using AlarmManager
. The Service
is running ok and I am stopping the Service
manually (clicking a Button
), but I need to stop the Service
after sometime (it may be 10 seconds). I can use this.stopSelf();
, but how do I call this.stopSelf();
after some given time?
This can easily be accomplished using timer
and timerTask
together.
I still do not know why this answer was not suggested and instead the provided answers do not provide the direct and simple solution.
In the service subclass, create these globally (you can create them not globally, but you might bump into issues)
//TimerTask that will cause the run() runnable to happen.
TimerTask myTask = new TimerTask()
{
public void run()
{
stopSelf();
}
};
//Timer that will make the runnable run.
Timer myTimer = new Timer();
//the amount of time after which you want to stop the service
private final long INTERVAL = 5000; // I choose 5 seconds
Now inside your onCreate()
of the service, do the following :
myTimer.schedule(myTask, INTERVAL);
This should stop the service after 5 seconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With