简体   繁体   English

Android-Activity onStop之后是否调用onServiceDisconnected?

[英]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 . 我有一个远程服务,我想使用该服务检查onPrepareOptionsMenu某些条件。 But sometimes I got "binder null" exception when I back from other activities. 但是,当我从其他活动中回来时,有时会出现“ binder null”异常。 I set binder to null in onServiceDisconnected . 我在onServiceDisconnected中将活页夹设置为null。

My question: 我的问题:

  1. Does onServiceDisconnected be called after activity onStop? 活动onStop之后是否onServiceDisconnected
  2. Is it better to bindService in onStart instead of onCreate ? onStart而不是onCreatebindService更好吗?
  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. 1)否。仅当服务意外终止(例如托管服务的进程崩溃onServiceDisconnected()时,才会调用onServiceDisconnected() 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. 这不会删除ServiceConnection本身-与服务的绑定将保持活动状态,并且在下次运行该服务时,您将收到对onServiceConnected(ComponentName,IBinder)的调用。

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. 2)通常,如果在活动停止时不需要连接到服务,那么可以,在onStart()绑定和在onStop()取消绑定是正确的方法。 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. 但是, 绑定服务文档指出,在某些情况下,在onCreate()进行绑定和在onDestroy()取消绑定也是可以的。

3) A local Service implies that the Service is in the same process as the consumer. 3)本地服务意味着该服务与使用者处于同一过程中。 A remote service is a Service that is in a different process. 远程服务是处于不同过程中的服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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