Reputation: 611
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?
Upvotes: 4
Views: 5225
Reputation: 871
In Kotlin you can use this code to stop service inside the onStartCommand() method:
Handler(Looper.getMainLooper()).postDelayed({ stopSelf() }, 10000)
Upvotes: 1
Reputation: 4717
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.
Upvotes: 5
Reputation: 5278
Intent
to start the Service
. Set the action
to a custom action, say "com.yourapp.action.stopservice"
. AlarmManager
, start the Intent
to start the Service
(whatever you are doing right now). This will be delivered to the onStartCommand()
of the Service
, if it is is already running.onStartCommand()
, check the action
of the incoming Intent
. If action.equals("com.yourapp.action.stopservice")
, stop the Service
using this.stopSelf()
.Upvotes: 0
Reputation: 2273
May be you should consider using IntentService? It will be stopped when there is no work for it so you don't need to manage its state by yourself.
Upvotes: 3
Reputation: 68177
Use postDelayed method of Handler
within service to get it done. For example:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
stopSelf();
}
}, 10000); //will stop service after 10 seconds
Upvotes: 3