乐闻世界logo
搜索文章和话题

What is the principle of Binder mechanism in Android and why use Binder

3月7日 19:50

Binder is the core mechanism for Inter-Process Communication (IPC) in Android systems and one of Android's distinctive features.

Why Android Chooses Binder

MethodProsCons
PipeSimpleUnidirectional, low efficiency
SocketUniversalHigh overhead, slow
Shared MemoryFastComplex synchronization, poor security
BinderEfficient, secure, easy to useSteep learning curve

Core Advantages of Binder

  1. Efficiency

    • Only one memory copy needed (traditional IPC needs two)
    • Based on C/S architecture, high communication efficiency
  2. Security

    • Kernel-level process identity verification (UID/PID)
    • Supports establishing private channels
  3. Usability

    • Encapsulates complex underlying implementation
    • Provides high-level interfaces like AIDL

How Binder Works

1. Core Components

  • Binder Driver: Located in kernel space, manages Binder communication
  • ServiceManager: Manages registration and query of all system services
  • Client/Server: Both parties in communication

2. Memory Mapping Mechanism

shell
Sender Process Binder Driver Receiver Process | | | | Data | Memory Map(MMAP) | | -------------> | ----------------> | | User Space | Kernel Space | User Space
  • Sender copies data to kernel space
  • Receiver accesses directly through memory mapping, no second copy needed

3. Communication Flow

shell
1. Server registers service → ServiceManager 2. Client queries service → ServiceManager 3. Client obtains Server's Binder proxy 4. Client calls Server methods through Binder proxy 5. Binder Driver completes data transfer

Binder Applications in Android

ActivityManagerService (AMS)

  • Manages Activity lifecycle
  • Process scheduling

WindowManagerService (WMS)

  • Window management
  • Screen display

PackageManagerService (PMS)

  • Application package management
  • Permission management

AIDL (Android Interface Definition Language)

java
// IRemoteService.aidl interface IRemoteService { int add(int a, int b); String getMessage(); }

AIDL compilation automatically generates:

  • Stub: Server-side implementation
  • Proxy: Client-side proxy

Key Points

  • Binder is Android-specific IPC mechanism
  • Understand one-copy memory mapping principle
  • Master basic AIDL usage
  • Binder thread pool defaults to 16 threads
  • Note Binder communication data size limit (around 1MB)
标签:Android