简体   繁体   中英

Android - Does onServiceDisconnected be called after Activity onStop?

I have a remote service, and I want to use the service to check some conditions in onPrepareOptionsMenu . But sometimes I got "binder null" exception when I back from other activities. I set binder to null in onServiceDisconnected .

My question:

  1. Does onServiceDisconnected be called after activity onStop?
  2. Is it better to bindService in onStart instead of onCreate ?
  3. Could you please explain simply the difference of local service and the remote service?

1) No. onServiceDisconnected() only gets called when the Service terminates unexpectedly, like when the process hosting the Service crashes. It will not be called when you unbind from the Service yourself. From the documentation :

Called when a connection to the Service has been lost. This typically happens when the process hosting the service has crashed or been killed. This does not remove the ServiceConnection itself -- this binding to the service will remain active, and you will receive a call to onServiceConnected(ComponentName, IBinder) when the Service is next running.

2) Generally, if you don't need to be connected to the Service while your Activity is stopped, then yes, binding in onStart() and unbinding in onStop() is the right way to go. The idea here is that you won't be wasting resources when your Activity is in the background. However, the documentation for bound services state that binding in onCreate() and unbinding in onDestroy() is OK too in some cases.

3) A local Service implies that the Service is in the same process as the consumer. A remote service is a Service that is in a different process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM