蓝色天空.知识 · 实践 · 创造
我的收藏
Android 教程目录 156章
课程介绍
Android / LEARN BY DOING

4.2.1 Service初涉

厘清 Service 组件与 Java 线程的本质区别,系统掌握 startService、bindService 及先启动再绑定混合模式下的完整生命周期回调与 IBinder 本地通信实践。

学完这一章,你能够

  • 厘清 Service 组件与 Java 线程的本质区别,系统掌握 startService、bindService 及先启动再绑定混合模式下的完整生命周期回调与 IBinder 本地通信实践。

线程基础概念与 Service 的本质区别

在学习 Android 四大组件之二 `Service`(服务)前,需要回顾进程、线程与线程生命周期(新建、就绪、运行、阻塞、终止)以及 Java 创建线程的三种常见方式:继承 `Thread`、实现 `Runnable`(最常用匿名实现或 Lambda 交给 `new Thread(runnable).start()` 启动)与实现 `Callable`。初学者常把 `Service` 与 `Thread` 混为一谈,实际上两者属于不同抽象层:`Thread` 是操作系统调度 CPU 的最小执行单元,而 `Service` 是无界面的应用组件,用于承载需在后台长期运行的逻辑(如音乐播放、后台下载或状态轮询),且 `Service` 默认直接运行在主线程中,执行耗时任务时仍需在内部另开工作线程。

Service 三种启动与绑定模式的生命周期详解

Service 围绕五个核心回调展开:`onCreate()` 在实例首次创建时仅执行一次;`onStartCommand(intent, flags, startId)` 在每次调用 `startService()` 时触发(取代早期 `onStart()`);`onBind(intent)` 必须实现并返回供客户端交互的 `IBinder` 对象;`onUnbind(intent)` 在全部已绑定客户端都断开连接时回调;`onDestroy()` 在服务销毁前仅调用一次。

根据使用方式,Service 呈现三条典型生命周期路径:第一,`startService()` 启动模式首次依次走 `onCreate -> onStartCommand`,后续重复启动只再调用 `onStartCommand`,服务生命周期独立于调用者,无论启动多少次只需一次 `stopService()`(或自身 `stopSelf()`)即可销毁;第二,`bindService(intent, conn, flags)` 绑定模式(常用 `BIND_AUTO_CREATE` 自动创建)依次走 `onCreate -> onBind`,并经 `ServiceConnection.onServiceConnected()` 将 `IBinder` 交给客户端,多客户端绑定时不会重复调用 `onBind()`,服务生命周期与所有绑定者共进退,直到所有客户端都 `unbindService()` 后触发 `onUnbind -> onDestroy`(注意主动调用 `unbindService()` 不会触发 `onServiceDisconnected()`,后者仅在远程宿主异常崩溃断开时触发);第三,先 `startService()` 再 `bindService()` 的混合模式下,调用 `unbindService()` 仅解绑而不销毁服务,若 `onUnbind()` 返回 `true` 则再次绑定会回调 `onRebind()`,必须同时满足已停止且全部解绑两个条件才会最终 `onDestroy()`。

startService 与 bindService 生命周期代码验证

第一个验证示例编写 `TestService1` 重写 `onCreate`、`onStartCommand`、`onBind`(返回 `null`)与 `onDestroy` 并在清单注册 `<service>`,在 `MainActivity` 中通过两个按钮触发 `startService()` 与 `stopService()`。连续点击启动可见 `onCreate()` 仅打印一次、`onStartCommand()` 随点击反复触发且 `onBind()` 全程未执行,点击一次停止即刻回调 `onDestroy()`。(需注意在 Android 5.0+ 上启动服务必须使用显式 `Intent` 或配合 `setPackage()`。)

第二个验证示例编写带后台计数线程的 `TestService2`,内部定义继承 `Binder` 的 `MyBinder` 暴露 `getCount()` 方法并由 `onBind()` 返回,同时在 `onDestroy()` 将循环退出标记 `quit` 置为 `true` 避免后台线程泄漏。客户端在 `MainActivity` 中定义 `ServiceConnection`,于 `onServiceConnected()` 拿到 `MyBinder` 后即可随时查询计数状态;重复点击绑定不会再次创建或回调 `onBind()`,解除绑定时依次触发 `onUnbind()` 与 `onDestroy()`。若 Activity 退出前忘记调用 `unbindService(conn)`,系统会报 `ServiceConnectionLeaked` 错误并强制解绑销毁服务,因此务必在 `onDestroy()` 中成对解绑。

运行 Service 三种生命周期状态机(startService / bindService / 混合重绑)验证

含完整源码 · 204 行
展开查看收起
python
"""Offline Android Service lifecycle verifier: startService, bindService, and hybrid start+bind+rebind."""
import json

VERSION = "CPython 3.12.14 offline Android component/IPC/Fragment verifier (Android SDK/emulator absent)"


class SimulatedServiceHost:
    """Models Android Service instance creation, start/stop, multi-client bind/unbind, and onRebind."""

    def __init__(self, allow_rebind: bool = True):
        self.created = False
        self.started = False
        self.start_id = 0
        self.bound_clients: set[str] = set()
        self.was_ever_bound = False
        self.all_unbound_returned_true = False
        self.allow_rebind = allow_rebind
        self.count = 0
        self.trace: list[str] = []
        self.conn_events: list[str] = []

    def _ensure_created(self):
        if not self.created:
            self.created = True
            self.trace.append("onCreate")

    def start_service(self):
        self._ensure_created()
        self.started = True
        self.start_id += 1
        self.trace.append(f"onStartCommand(startId={self.start_id})")

    def stop_service(self):
        if not self.created:
            return
        self.started = False
        self._maybe_destroy()

    def bind_service(self, client_id: str, auto_create: bool = True):
        if not self.created and auto_create:
            self._ensure_created()
        if not self.created:
            return None
        first_active = len(self.bound_clients) == 0
        self.bound_clients.add(client_id)
        if first_active:
            if not self.was_ever_bound:
                self.was_ever_bound = True
                self.trace.append("onBind")
            elif self.all_unbound_returned_true:
                self.all_unbound_returned_true = False
                self.trace.append("onRebind")
        self.conn_events.append(f"{client_id}:onServiceConnected")
        return self

    def unbind_service(self, client_id: str):
        if client_id not in self.bound_clients:
            return
        self.bound_clients.remove(client_id)
        # Note: normal unbindService does NOT invoke ServiceConnection.onServiceDisconnected
        if not self.bound_clients:
            self.trace.append("onUnbind")
            if self.allow_rebind:
                self.all_unbound_returned_true = True
            self._maybe_destroy()

    def tick_worker(self, ticks: int):
        self.count += ticks

    def _maybe_destroy(self):
        if self.created and not self.started and not self.bound_clients:
            self.trace.append("onDestroy")
            self.created = False
            self.was_ever_bound = False
            self.all_unbound_returned_true = False


def case_thread_vs_service_and_start_service_lifecycle():
    thread_states = ["NEW", "RUNNABLE", "RUNNING", "TIMED_WAITING", "TERMINATED"]
    svc = SimulatedServiceHost()
    svc.start_service()
    svc.start_service()
    svc.start_service()
    alive_after_caller_finished = svc.created and svc.started
    svc.stop_service()

    actual = {
        "thread_states": thread_states,
        "service_runs_on_main_thread": True,
        "start_trace": svc.trace,
        "alive_after_caller_finished": alive_after_caller_finished,
        "destroyed_after_single_stop": not svc.created,
    }
    expected = {
        "thread_states": ["NEW", "RUNNABLE", "RUNNING", "TIMED_WAITING", "TERMINATED"],
        "service_runs_on_main_thread": True,
        "start_trace": [
            "onCreate",
            "onStartCommand(startId=1)",
            "onStartCommand(startId=2)",
            "onStartCommand(startId=3)",
            "onDestroy",
        ],
        "alive_after_caller_finished": True,
        "destroyed_after_single_stop": True,
    }
    return {
        "name": "thread_vs_service_and_start_service_lifecycle",
        "summary": "验证线程生命周期与 Service 主线程组件差异,以及多次 startService 仅调用一次 onCreate、单次 stopService 即触发 onDestroy。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_bind_service_lifecycle_and_binder_ipc():
    svc = SimulatedServiceHost()
    binder1 = svc.bind_service("ClientA", auto_create=True)
    binder1.tick_worker(5)
    binder2 = svc.bind_service("ClientB", auto_create=True)
    count_read = binder2.count
    # Unbinding ClientA while ClientB still bound keeps Service alive
    svc.unbind_service("ClientA")
    alive_with_one_client = svc.created
    svc.unbind_service("ClientB")

    actual = {
        "same_binder_instance": binder1 is binder2,
        "count_read_via_binder": count_read,
        "alive_with_one_client": alive_with_one_client,
        "destroyed_when_all_unbound": not svc.created,
        "trace": svc.trace,
        "conn_events": svc.conn_events,
    }
    expected = {
        "same_binder_instance": True,
        "count_read_via_binder": 5,
        "alive_with_one_client": True,
        "destroyed_when_all_unbound": True,
        "trace": ["onCreate", "onBind", "onUnbind", "onDestroy"],
        "conn_events": ["ClientA:onServiceConnected", "ClientB:onServiceConnected"],
    }
    return {
        "name": "bind_service_lifecycle_and_binder_ipc",
        "summary": "验证 bindService 多客户端共享 IBinder、通过 MyBinder.getCount() 读取状态、全部解绑后才销毁且正常解绑不回调 onServiceDisconnected。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_hybrid_start_and_bind_rebind_lifecycle():
    svc = SimulatedServiceHost(allow_rebind=True)
    svc.start_service()
    svc.bind_service("ClientA")
    svc.unbind_service("ClientA")
    still_alive_after_unbind = svc.created
    # Re-binding after onUnbind returned true invokes onRebind instead of onBind
    svc.bind_service("ClientB")
    svc.stop_service()
    still_alive_after_stop_while_bound = svc.created
    svc.unbind_service("ClientB")

    actual = {
        "still_alive_after_unbind": still_alive_after_unbind,
        "still_alive_after_stop_while_bound": still_alive_after_stop_while_bound,
        "destroyed_only_after_both_stop_and_unbind": not svc.created,
        "trace": svc.trace,
    }
    expected = {
        "still_alive_after_unbind": True,
        "still_alive_after_stop_while_bound": True,
        "destroyed_only_after_both_stop_and_unbind": True,
        "trace": [
            "onCreate",
            "onStartCommand(startId=1)",
            "onBind",
            "onUnbind",
            "onRebind",
            "onUnbind",
            "onDestroy",
        ],
    }
    return {
        "name": "hybrid_start_and_bind_rebind_lifecycle",
        "summary": "验证先 startService 再 bindService 混合模式:解绑不销毁、onUnbind 返回 true 时再次绑定回调 onRebind,直至同时 stop 且全部 unbind 才 onDestroy。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_thread_vs_service_and_start_service_lifecycle(),
        case_bind_service_lifecycle_and_binder_ipc(),
        case_hybrid_start_and_bind_rebind_lifecycle(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证多次 startService 单次 onCreate 与单次 stop 销毁、多客户端 bindService 共享 IBinder 与计数读取,以及混合模式 onUnbind 返回 true 触发 onRebind。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1829.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1940.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

不会。混合模式下 Service 同时受“已启动”和“已绑定”两个状态保护,仅解除绑定只会回调 onUnbind(),必须再调用 stopService()(或服务自身 stopSelf())后才会进入 onDestroy()。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习