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

4.2.3 Service精通

剖析 Android Binder 跨进程通信(IPC)原理与性能安全优势,详解 AIDL 基础与复杂 Parcelable 对象编解码、直接 Binder.onTransact 通信,以及 Android 5.0+ Service 显式 Intent 规则。

学完这一章,你能够

  • 剖析 Android Binder 跨进程通信(IPC)原理与性能安全优势,详解 AIDL 基础与复杂 Parcelable 对象编解码、直接 Binder.onTransact 通信,以及 Android 5.0+ Service 显式 Intent 规则。

Binder IPC 架构、一次拷贝优势与远程存活检测

`IBinder` 是 Android 高性能跨进程通信(IPC)的基础协议接口,工程上不直接实现 `IBinder`,而是继承系统基类 `Binder`。其核心交互由客户端调用 `transact()` 与服务端响应 `Binder.onTransact()` 配对完成,请求与返回数据通过 `Parcel` 缓冲区封送(同步阻塞直至服务端线程池返回结果,且支持跨进程递归调用)。检测远程 Binder 对象是否仍存活提供三种手段:`transact()` 在对端进程死亡时抛出 `RemoteException`、`pingBinder()` 返回 `false`,以及通过 `linkToDeath()` 注册 `IBinder.DeathRecipient` 死亡代理回调。

Binder 体系由四类角色协同:Client(调用代理)、Server(服务实现)、ServiceManager(句柄路由注册中心)与内核态 Binder Driver(驱动层)。Android 选用 Binder 而非传统 Linux IPC 源于三方面优势:一是可靠性,原生契合移动端 Client-Server 架构;二是传输性能,借助内存映射机制数据仅需拷贝 1 次(对比共享内存 0 次但同步复杂,而 Socket、管道与消息队列均需 2 次拷贝);三是安全性,内核直接为每个 IPC 事务附带调用方真实的 UID/PID 身份,避免用户态伪造。

AIDL 基础通信与复杂 Parcelable 对象传输

AIDL(Android Interface Definition Language)用于声明跨进程接口,由 SDK 工具编译生成包含 `Stub` 与 `Proxy` 内部类的同名 Java 接口。编写 `.aidl` 需遵守四条规范:接口名与文件名一致;接口和方法不得添加 `public`/`private`/`static`/`final` 等修饰符;默认支持 Java 基本类型、`String`、`CharSequence`、`List` 与 `Map`;自定义 `Parcelable` 与其他 AIDL 接口即使同包也必须显式 `import`。在 Android Studio 中应将 `.aidl` 放在 `src/main/aidl/<包名>` 下并重新构建。以 `IPerson.aidl` 为例,生成的 `IPerson.Stub.asInterface(IBinder)` 会先通过 `queryLocalInterface()` 判断是否同进程——同进程直接返回本地 `Stub`,跨进程则包装为 `Proxy` 经 `Parcel` 封送 `DESCRIPTOR` 与参数。服务端继承 `IPerson.Stub` 并在 `Service.onBind()` 中返回该 `binder`(需特别注意原教材示例 `AIDLService.onBind()` 误写了 `return null;`,实际运行必须返回 `return binder;` 否则客户端 `asInterface(null)` 得到空对象)。

当跨进程方法需要传输自定义对象(如 `Person` 入参与 `Salary` 返回值)时,实体类必须实现 `Parcelable` 接口:覆写 `writeToParcel(Parcel, int)` 与 `describeContents()`(常规返回 `0`),并提供名为 `CREATOR` 的 `static final Parcelable.Creator<T>` 实现 `createFromParcel()` 与 `newArray()`——写入与读取字段的顺序必须严格一致。在 `.aidl` 中还须为每个实体建同名声明文件(如 `parcelable Person;`),并在接口方法参数前注明方向指示符 `in`(客户端传给服务端)、`out`(服务端回填给客户端)或 `inout`(双向同步)。在 `ISalary` 示例中,`AidlService` 用 `Map<Person, Salary>` 检索薪资,因此 `Person` 覆写了 `hashCode()` 与 `equals()`;客户端拷贝完全一致的包名与 AIDL 文件,绑定服务后通过 `ISalary.Stub.asInterface(service)` 发起跨进程查询。

直接 Binder.onTransact 通信与 Android 5.0+ Service 显式启动约束

若无需自动生成 AIDL 样板代码,也可直接在服务端自定义 `Binder` 子类覆写 `onTransact(int code, Parcel data, Parcel reply, int flags)`:按约定的事务码(如 `0x001`)执行 `data.enforceInterface(DESCRIPTOR)` 校验令牌,读取入参并将结果写入 `reply`;客户端绑定获取原始 `IBinder` 后,手动 `Parcel.obtain()` 写入相同令牌与参数,调用 `mIBinder.transact(0x001, _data, _reply, 0)` 并读取返回值,最后务必在 `finally` 块中调用 `_data.recycle()` 与 `_reply.recycle()` 释放缓冲区。

自 Android 5.0(API 21)起,出于安全考量,系统严格要求启动或绑定 `Service` 的 `Intent` 必须显式化(Service Intent must be explicit),使用纯隐式 Action 调用 `startService()` 或 `bindService()` 会直接抛出 `IllegalArgumentException`。本地服务应传入具体类名 `new Intent(context, TargetService.class)`;跨进程绑定远程服务时,应在 Action 基础上调用 `service.setPackage("com.jay.aidlserver")`(或直接指定目标 `ComponentName`)以确保明确路由。同时在 Android 11+(API 30)跨应用查询或绑定其他应用服务时,还需在客户端清单配置 `<queries>` 声明包可见性。

运行 Binder 一次拷贝/存活检测、AIDL Stub/Proxy 编解码与 Parcelable/onTransact 验证

含完整源码 · 300 行
展开查看收起
python
"""Offline Android Binder IPC, AIDL Stub/Proxy Parcel marshaling, Parcelable, and API 21 explicit Service verifier."""
import json
import struct

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


class SimulatedParcel:
    """Deterministic binary Parcel stream enforcing strict write/read order and interface token check."""

    def __init__(self):
        self._buf = bytearray()
        self._pos = 0

    def write_interface_token(self, descriptor: str):
        self.write_string(descriptor)

    def enforce_interface(self, expected: str):
        got = self.read_string()
        if got != expected:
            raise PermissionError(f"SecurityException: interface mismatch {got} != {expected}")

    def write_int(self, val: int):
        self._buf.extend(struct.pack(">i", val))

    def read_int(self) -> int:
        val, = struct.unpack(">i", self._buf[self._pos:self._pos + 4])
        self._pos += 4
        return val

    def write_string(self, s: str | None):
        if s is None:
            self.write_int(-1)
            return
        raw = s.encode("utf-8")
        self.write_int(len(raw))
        self._buf.extend(raw)

    def read_string(self) -> str | None:
        length = self.read_int()
        if length == -1:
            return None
        raw = bytes(self._buf[self._pos:self._pos + length])
        self._pos += length
        return raw.decode("utf-8")

    def write_no_exception(self):
        self.write_int(0)

    def read_exception(self):
        code = self.read_int()
        if code != 0:
            raise RuntimeError(f"RemoteException(code={code})")


def case_binder_ipc_architecture_and_copy_semantics():
    copy_counts = {
        "shared_memory": 0,
        "binder": 1,
        "socket": 2,
        "pipe": 2,
        "message_queue": 2,
    }

    death_notifications = []

    class RemoteBinderHandle:
        def __init__(self, alive: bool = True):
            self.alive = alive
            self.recipients = []

        def ping_binder(self) -> bool:
            return self.alive

        def link_to_death(self, cb):
            self.recipients.append(cb)

        def simulate_process_death(self):
            self.alive = False
            for cb in self.recipients:
                cb()

        def transact(self):
            if not self.alive:
                return "RemoteException"
            return "SYNC_OK"

    handle = RemoteBinderHandle(alive=True)
    handle.link_to_death(lambda: death_notifications.append("binderDied"))
    before_death = (handle.ping_binder(), handle.transact())
    handle.simulate_process_death()
    after_death = (handle.ping_binder(), handle.transact())

    actual = {
        "ipc_copy_counts": copy_counts,
        "before_death": list(before_death),
        "after_death": list(after_death),
        "death_notifications": death_notifications,
        "kernel_uid_pid_trusted": True,
    }
    expected = {
        "ipc_copy_counts": {"shared_memory": 0, "binder": 1, "socket": 2, "pipe": 2, "message_queue": 2},
        "before_death": [True, "SYNC_OK"],
        "after_death": [False, "RemoteException"],
        "death_notifications": ["binderDied"],
        "kernel_uid_pid_trusted": True,
    }
    return {
        "name": "binder_ipc_architecture_and_copy_semantics",
        "summary": "验证 Binder 一次拷贝性能语义、同步 transact 语义、pingBinder/linkToDeath/RemoteException 远程存活检测机制。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_aidl_simple_query_and_parcel_marshaling():
    descriptor = "com.jay.aidl.IPerson"
    tx_query_person = 1  # FIRST_CALL_TRANSACTION + 0
    names = ["成员A", "成员B", "成员C", "成员D", "成员E"]

    class IPersonStub:
        def query_local_interface(self, desc: str):
            return self if desc == descriptor else None

        def query_person(self, num: int) -> str | None:
            if 1 <= num <= len(names):
                return names[num - 1]
            return None

        def on_transact(self, code: int, data: SimulatedParcel, reply: SimulatedParcel, flags: int) -> bool:
            if code == tx_query_person:
                data.enforce_interface(descriptor)
                arg0 = data.read_int()
                res = self.query_person(arg0)
                reply.write_no_exception()
                reply.write_string(res)
                return True
            return False

    class IPersonProxy:
        def __init__(self, remote_stub: IPersonStub):
            self.remote = remote_stub

        def query_person(self, num: int) -> str | None:
            data = SimulatedParcel()
            reply = SimulatedParcel()
            data.write_interface_token(descriptor)
            data.write_int(num)
            self.remote.on_transact(tx_query_person, data, reply, 0)
            reply.read_exception()
            return reply.read_string()

    def as_interface(binder, same_process: bool):
        if binder is None:
            return None
        if same_process:
            return binder.query_local_interface(descriptor)
        return IPersonProxy(binder)

    stub = IPersonStub()
    local_iface = as_interface(stub, same_process=True)
    remote_proxy = as_interface(stub, same_process=False)

    # Note: source AIDLService.onBind accidentally returned null -> asInterface(null) returns null!
    null_onbind_result = as_interface(None, same_process=False)

    actual = {
        "local_is_stub": isinstance(local_iface, IPersonStub),
        "remote_is_proxy": isinstance(remote_proxy, IPersonProxy),
        "remote_query_3": remote_proxy.query_person(3),
        "remote_query_oob": remote_proxy.query_person(9),
        "null_onbind_returns_none": null_onbind_result is None,
    }
    expected = {
        "local_is_stub": True,
        "remote_is_proxy": True,
        "remote_query_3": "成员C",
        "remote_query_oob": None,
        "null_onbind_returns_none": True,
    }
    return {
        "name": "aidl_simple_query_and_parcel_marshaling",
        "summary": "验证 AIDL Stub/Proxy 跨进程 Parcel 编解码、asInterface 同进程直调与跨进程代理分支,以及服务端 onBind 误返回 null 的隐患。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_aidl_complex_parcelable_and_raw_transact():
    # Parcelable Person (equality by name) & Salary
    class Person:
        def __init__(self, pid: int, name: str):
            self.id = pid
            self.name = name

        def write_to_parcel(self, p: SimulatedParcel):
            p.write_int(self.id)
            p.write_string(self.name)

        @staticmethod
        def create_from_parcel(p: SimulatedParcel):
            return Person(p.read_int(), p.read_string())

        def __hash__(self):
            return hash(self.name)

        def __eq__(self, other):
            return isinstance(other, Person) and self.name == other.name

    class Salary:
        def __init__(self, role: str, amount: int):
            self.role = role
            self.amount = amount

        def write_to_parcel(self, p: SimulatedParcel):
            p.write_string(self.role)
            p.write_int(self.amount)

        @staticmethod
        def create_from_parcel(p: SimulatedParcel):
            return Salary(p.read_string(), p.read_int())

    salary_map = {
        Person(1, "Jay"): Salary("Engineer", 2000),
        Person(2, "GEM"): Salary("Singer", 20000),
    }

    # Client sends Person(99, "GEM") -> marshaled -> server looks up by name equality
    req = SimulatedParcel()
    req.write_interface_token("com.jay.example.aidl.ISalary")
    Person(99, "GEM").write_to_parcel(req)

    rep = SimulatedParcel()
    req.enforce_interface("com.jay.example.aidl.ISalary")
    owner = Person.create_from_parcel(req)
    sal = salary_map[owner]
    rep.write_no_exception()
    sal.write_to_parcel(rep)

    rep.read_exception()
    got_sal = Salary.create_from_parcel(rep)

    # Direct Binder.onTransact(0x001) without AIDL
    raw_names = ["Zero", "One", "Two"]
    raw_data = SimulatedParcel()
    raw_reply = SimulatedParcel()
    raw_data.write_interface_token("IPCService")
    raw_data.write_int(2)
    raw_data.enforce_interface("IPCService")
    idx = raw_data.read_int()
    raw_reply.write_no_exception()
    raw_reply.write_string(raw_names[idx])
    raw_reply.read_exception()
    raw_res = raw_reply.read_string()

    # Android 5.0+ (API 21) explicit Service Intent rule
    def check_service_intent(api_level: int, has_component: bool, has_package: bool) -> str:
        if api_level >= 21 and not (has_component or has_package):
            return "IllegalArgumentException: Service Intent must be explicit"
        return "ALLOWED"

    actual = {
        "parcelable_salary_role": got_sal.role,
        "parcelable_salary_amount": got_sal.amount,
        "raw_binder_transact_result": raw_res,
        "aidl_direction_tags": ["in", "out", "inout"],
        "api21_implicit_service": check_service_intent(21, False, False),
        "api21_with_package": check_service_intent(21, False, True),
    }
    expected = {
        "parcelable_salary_role": "Singer",
        "parcelable_salary_amount": 20000,
        "raw_binder_transact_result": "Two",
        "aidl_direction_tags": ["in", "out", "inout"],
        "api21_implicit_service": "IllegalArgumentException: Service Intent must be explicit",
        "api21_with_package": "ALLOWED",
    }
    return {
        "name": "aidl_complex_parcelable_and_raw_transact",
        "summary": "验证复杂 Parcelable(Person/Salary)顺序序列化与哈希键查询、直接 Binder.onTransact 通信,以及 Android 5.0+ 显式 Service Intent 强制校验。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_binder_ipc_architecture_and_copy_semantics(),
        case_aidl_simple_query_and_parcel_marshaling(),
        case_aidl_complex_parcelable_and_raw_transact(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证 Binder 拷贝次数与 DeathRecipient、IPerson asInterface 本地/跨进程分支与 onBind 返空隐患、Person/Salary Parcelable 往返及 API 21 显式 Service 约束。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

asInterface() 会先调用 obj.queryLocalInterface(DESCRIPTOR):若客户端与服务端位于同一进程,直接返回本地 Stub 实现对象避免序列化开销;若跨进程则查询返回 null,转而创建内部 Proxy 代理对象,由其将参数打包进 Parcel 并经 Binder 驱动调用 transact()。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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