Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android service need to stop after sometime

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?

like image 485
Humayun Kabir Avatar asked Sep 21 '25 09:09

Humayun Kabir


1 Answers

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.

like image 61
tony9099 Avatar answered Sep 23 '25 00:09

tony9099