"""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()
本例需在 Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。
入口文件:projects/android-tutorial-service-1-lab/explore-tutorial-service-1.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-service-1.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1940.zip