gpt4 book ai didi

Android - 在调用 stopService 时销毁服务

转载 作者:行者123 更新时间:2023-11-29 20:54:35 30 4
gpt4 key购买 nike

我有一个后台服务,当在 UI 上按下相应的按钮(“连接”和“分别断开连接”)。

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

我该怎么做才能确保在调用 stopService() 时立即执行这些清理操作(只要有人单击“断开连接”按钮就会触发)?我必须采用bindService()方法,还是有其他方法?

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

最佳答案

来自文档:

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() 尽快终止服务可能还有其他因素使其保持 Activity 状态(因为您说有时需要onDestory() 被调用的时间似乎是这样)。您可能希望监视您的服务以了解可能阻止服务及时关闭的传入 Activity 。

关于Android - 在调用 stopService 时销毁服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28150241/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com