I created a service that can be started via the startService()
method, but it also be bound by the applications. I wish that it can be started only via the startService()
method, or in other words, applications should be able to bind to it only when the service is already started.
- The service should be started manually and not when an application binds to it.
- If the service is running, applications can bind to it.
- If the service is not running, when an application tries to bind to it, the service should not start.
However, the default behavior is quite different: in fact, Android starts the service automatically when an application wants to bind to it. I would like to know if is possible to modify this behavior to achieve the above requirement.
If this is not possible, the only alternative would be to stop the service if it has been initiated as a result of a bindService()
. Here are the changes to my service class in order to use this way...
// It says if the service was started manually.
private boolean mCorrectlyStarted = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOG_TAG, "onStartCommand()");
mCorrectlyStarted = true; // the service is started manually: ok!
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
Log.i(LOG_TAG, String.format("onBind(intent: %s)", intent));
if (mCorrectlyStarted) {
return binder;
}
else {
stopSelf(); // although I make this call, the service is not stopped
return null;
}
}
Why do my changes do not have the desired effect?
It might be good that the service starts when an application invokes the bindService()
method, but after verifying that it was not started manually, it should stop itself.