2

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.

  1. The service should be started manually and not when an application binds to it.
  2. If the service is running, applications can bind to it.
  3. 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.

4

1 回答 1

0

诸如 Activity 之类的东西被调用的事实bindService()意味着某人仍然绑定到该服务。调用stopSelf()不会破坏服务,因为从技术上讲,服务仍受活动约束。

unbindService一旦最终被 Activity 调用,它将被销毁。绑定和启动服务是正交的。

我不确定你想用这个设计实现什么,也许提供更多信息,说明为什么你希望服务在绑定之前启动?

于 2012-08-13T05:33:08.000 回答