Reputation: 6884
Is there a way to check that the service is not already running before starting it?
If it could be in the onCreate() of the service it will be even better,
Thank you!
Upvotes: 22
Views: 8705
Reputation: 6703
I just tested on Android 9 (API 28) that you can start the same service with the same Intent
as many times as you want:
onCreate() {
startMyService();
startMyService();
startMyService();
startMyService();
startMyService();
startMyService();
startMyService();
startMyService();
startMyService();
startMyService();
}
private void startMyService() {
Intent serviceIntent = new Intent(this, MyService.class);
ContextCompat.startForegroundService(this, serviceIntent);
}
One way to avoid this is to stop it before starting it by passing the identical Intent
:
private void startMyService() {
Intent serviceIntent = new Intent(this, MyService.class);
stopService(serviceIntent); // <<<<< this line makes sure that you don't start it twice or more times
ContextCompat.startForegroundService(this, serviceIntent);
}
Upvotes: 0
Reputation: 6884
fix it with a boolean/flag in the service. (A service can only be started once)
Upvotes: -2
Reputation: 6709
You can't start a service twice, it will remain running if you try to start it again. Link to the Android docs.
Upvotes: 36