Android - 在调用 stopService 时销毁服务

Android - destroying service on calling stopService

我有一个后台服务,当在 UI("connect" 和 "disconnect" 分别)。

我在服务停止时执行大量清理操作,并且我将这些操作放在服务的 onDestroy() 中,假设只要调用 stopService() 就会调用它。但是,我观察到在调用 stopService() 时不会立即调用 onDestroy() 。它可能会在某个时间被调用,或者在 非常 很长时间之后被调用。

如何确保在调用 stopService() 时立即执行这些清理操作(只要有人单击 "disconnect" 按钮就会触发)?我采用bindService()方法,还是有其他方法?

注意:该服务 运行 在同一个应用程序中属于它自己的进程。

调用 stopService() 中的 finish()。这将调用 onDestroy()

来自文档:

Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.

However, if your service handles multiple requests to onStartCommand() concurrently, then you shouldn't stop the service when you're done processing a start request, because you might have since received a new start request (stopping at the end of the first request would terminate the second one). To avoid this problem, you can use stopSelf(int) to ensure that your request to stop the service is always based on the most recent start request. That is, when you call stopSelf(int), you pass the ID of the start request (the startId delivered to onStartCommand()) to which your stop request corresponds. Then if the service received a new start request before you were able to call stopSelf(int), then the ID will not match and the service will not stop.

由于 stopSelf()stopService() 尽快终止服务可能还有其他因素使其保持活动状态(因为您说 onDestory() 有时需要很长时间被称为似乎是这种情况)。您可能希望监视您的服务是否有传入 activity,这可能会阻止服务及时关闭。