我已经阅读了很多有关 Android 服务的信息。据我了解,生命周期是:
void onCreate()
void onStart(Intent intent)
...
void onDestroy()
http://www.linuxtopia.org/online_books/android/devguide/guide/topics/fundamentals.html
但是没有 onStop 方法。 问题:
- 为什么没有停止方法?
- 在我的服务上发出 stopService 请求时会发生什么? (从外部,也许是 Android 本身)。我可以检测到此事件吗?
- 我想强制(或至少验证)我的服务是进程中的单例。我该怎么做(或者 Android 在幕后强制执行)?
对于上下文,我有一些我想在服务运行时分配和释放的资源(在“启动”中),还有另一组资源我想在服务运行时分配和释放“创建”状态。
最佳答案
As I understand, the lifecycle is:
onStart()
已经被弃用了几年。 onStartCommand()
是当前的生命周期方法。
Why isn't there a stop method?
因为不需要一个。
What happens when a stopService request is made on my Service?
您将被调用 onDestroy()
。
Can I detect this event?
您可以覆盖 onDestroy()
。
I'd like to enforce (or at least verify) that my service is a singleton within a process. How can I do this (or does Android enforce this behind the scenes)?
服务是自然的单例。在任何给定时间都会有 0 或 1 个服务实例。
For context, I have some resources I'd like to allocate and release while the service is running (in a "started"), and another set of resources I'd like to allocate and release while the service is a "created" state.
“创建”状态同时用于命令模式(startService()
和 onStartCommand()
)和绑定(bind)模式(bindService()
和 onBind()
)。因此,如果您调用 startService()
,您的服务将完全处于“创建”状态,希望不到一毫秒。
关于android - 为什么没有 Service.onStop 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10237253/