android - 为什么没有 Service.onStop 方法?

标签 android android-service

我已经阅读了很多有关 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/

相关文章:

java - Android 9.0 Activity 泄露了最初添加的窗口

android - 根据视频宽度和高度旋转屏幕

Android:从后台服务中获取网页的 'screenshot'?

java - 从正在运行的服务更新 Activity UI

android - 从服务调用时 Activity 重新启动

android - 在 Eclipse 中,Android 应用程序使用 Java 7,其他 Java 应用程序使用 Java 8

android - 在Android中实现故事功能

java - 为自定义按钮充气时发生 ClassNotFoundException(在手机上有效;在平板电脑上异常)

android - 从 Delphi (RAD Studio) 中的 Android 服务写入 SQLite 数据库

android - 无法恢复 Activity : not allowed to start service Intent, 应用程序在后台