在 Android 开发中,Handler
和 Binder
是两个核心概念,分别用于不同场景的线程通信和跨进程通信(IPC)。以下是它们的主要区别:
1. 核心功能
Handler | Binder |
---|---|
用于线程间通信(同一进程内) | 用于跨进程通信(IPC,不同进程间) |
主要解决 UI 线程不能直接处理耗时操作的问题 | 实现不同进程间的对象方法调用和数据共享 |
基于消息队列(MessageQueue)和 Looper 机制 | 基于 Linux 内核的 Binder 驱动 |
2. 工作原理
Handler
- 消息队列(MessageQueue):存储待处理的消息(Message)。
- Looper:循环从消息队列中取出消息,并分发给对应的 Handler。
- Handler:发送消息(
sendMessage()
)和处理消息(handleMessage()
)。
示例流程:
- 子线程通过 Handler 发送消息到主线程的消息队列。
- 主线程的 Looper 取出消息,调用 Handler 的
handleMessage()
方法更新 UI。
Binder
- C/S 架构:客户端(Client)通过 Binder 调用服务端(Server)的方法。
- Binder 驱动:内核层实现进程间内存映射和数据传输。
- IBinder 接口:所有 Binder 对象必须实现的接口,定义跨进程方法调用的规范。
示例流程:
- 服务端(如 SystemServer)注册 Binder 服务。
- 客户端通过
ServiceManager
获取服务的 Binder 引用。 - 客户端调用 Binder 代理对象的方法,数据通过 Binder 驱动传输到服务端。
3. 使用场景
Handler
- 更新 UI(例如在子线程中完成网络请求后刷新界面)。
- 定时任务(通过
postDelayed()
实现)。 - 异步任务的回调处理。
示例代码:
// 在主线程创建 Handler
Handler handler = new Handler(Looper.getMainLooper()) {@Overridepublic void handleMessage(Message msg) {// 更新 UItextView.setText("更新后内容");}
};// 在子线程发送消息
new Thread(() -> {// 耗时操作handler.sendEmptyMessage(0);
}).start();
Binder
- 系统服务调用(如 ActivityManager、WindowManager)。
- 自定义跨进程服务(如音乐播放器服务)。
- ContentProvider(基于 Binder 实现)。
示例代码:
// 定义 AIDL 接口(如 IMyService.aidl)
interface IMyService {int add(int a, int b);
}// 服务端实现 Binder
public class MyService extends Service {private final IMyService.Stub binder = new IMyService.Stub() {@Overridepublic int add(int a, int b) {return a + b;}};@Overridepublic IBinder onBind(Intent intent) {return binder;}
}// 客户端调用
ServiceConnection connection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {IMyService myService = IMyService.Stub.asInterface(service);int result = myService.add(1, 2);}
};
4. 性能对比
维度 | Handler | Binder |
---|---|---|
开销 | 低(线程间消息传递) | 高(涉及内核态切换和数据拷贝) |
延迟 | 毫秒级 | 百微秒级(跨进程时) |
适用数据量 | 小(消息携带少量数据) | 中等(单次传输上限约 1MB) |
5. 核心区别总结
对比项 | Handler | Binder |
---|---|---|
通信范围 | 同一进程内的线程间 | 不同进程间 |
实现机制 | 消息队列 + Looper | Linux Binder 驱动 + AIDL |
核心类 | Handler , Message , Looper | IBinder , Service , AIDL |
典型场景 | 更新 UI、异步任务 | 系统服务调用、自定义 IPC |