Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 104 ยท Shipping to Users

Binder, AIDL, Messenger and the NDK

How Android apps talk across process boundaries with Binder, bound services, Messenger and AIDL, plus Parcelable, one-way calls and a first look at the NDK, JNI and CMake.

Every Android app runs in its own process, with its own memory. That isolation is a security feature, but sometimes two processes must talk: your app asks the system for the clipboard, a music app lets other apps control playback, a banking SDK runs in a separate process for safety. This is inter-process communication (IPC), and on Android almost all of it travels through one mechanism: Binder.

This lesson shows how Binder works, the three ways to expose a service to other processes (extending Binder, Messenger, AIDL), what Parcelable and oneway mean, and then takes a first look at the other boundary you may cross: calling native C/C++ code through the NDK and JNI. Real IPC needs an Android device with two processes, so the real code is read-only. The TryIts are stand-ins: a pure-Kotlin model of a marshalled Binder call, and a model of a Messenger's message queue.

Binder in one page

Binder is a kernel-supported RPC system. A client holds a proxy object. When it calls a method on the proxy, the arguments are marshalled (flattened into a byte buffer called a Parcel), sent through the Binder driver to the other process, unmarshalled by a stub, and the real method runs. The result travels back the same way.

sequenceDiagram
    participant C as Client process
    participant D as Binder driver
    participant S as Service process
    C->>C: proxy.add(2, 3) writes Parcel
    C->>D: transact(code, parcel)
    D->>S: deliver to a binder thread
    S->>S: stub.onTransact reads Parcel, runs add()
    S->>D: reply Parcel
    D->>C: result 5

A synchronous Binder call. The client thread waits until the reply arrives.

Facts worth remembering:

  • A synchronous call blocks the calling thread. If you make it from the main thread and the other process is slow, you can get an ANR, see Performance and Profiling.
  • Incoming calls run on a pool of binder threads in the service process, not on its main thread. Your service code must be thread-safe.
  • All transactions share a buffer of about 1 MB per process. Large payloads throw TransactionTooLargeException; pass a file descriptor or a URI instead of big blobs.
  • The system uses Binder everywhere: getSystemService(), activity starts and content providers (Content Providers) all sit on top of it.

Bound services, three flavors

You met bound services in Services and Notifications: onBind() returns an IBinder. What that binder is decides how clients talk to it.

Approach Same process? Threading Use it when
Extend Binder Same process only Caller's thread A private service inside your own app
Messenger Cross-process One thread, one queue (serialized) Simple request and reply with few message types
AIDL Cross-process Multi-threaded A real API: many methods, typed arguments, concurrent clients

Extending Binder (same process)

If the service lives in your own process, skip IPC machinery and return a small Binder that hands out the service itself:

Kotlin
// read-only example: needs Android
class PlayerService : Service() {
    inner class LocalBinder : Binder() {
        fun service(): PlayerService = this@PlayerService
    }
    private val binder = LocalBinder()
    override fun onBind(intent: Intent): IBinder = binder

    fun play(trackId: Long) { /* ... */ }
}

The activity binds with a ServiceConnection and receives the binder in onServiceConnected, then calls (binder as LocalBinder).service().play(7) directly. Remember to unbindService() in the matching lifecycle callback.

Messenger

A Messenger wraps a Handler and lets other processes send Message objects to it. Messages are queued and handled one at a time on the handler's thread, which spares you from locking.

Kotlin
// read-only example: needs Android
const val MSG_SAY_HELLO = 1

class HelloService : Service() {
    private class IncomingHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MSG_SAY_HELLO -> {
                    val name = msg.data.getString("name")
                    // answer through the Messenger the client put in replyTo
                    msg.replyTo?.send(Message.obtain(null, MSG_SAY_HELLO, 0, 0).apply {
                        data = bundleOf("greeting" to "Hello, $name")
                    })
                }
                else -> super.handleMessage(msg)
            }
        }
    }

    private val messenger = Messenger(IncomingHandler(Looper.getMainLooper()))
    override fun onBind(intent: Intent): IBinder = messenger.binder
}

A client builds Messenger(binderFromService) in onServiceConnected and sends messages with send(). A message can carry only what fits in a Bundle and a few int fields, which is the main limit of this style.

AIDL

The Android Interface Definition Language describes an interface in a .aidl file, and the build generates the proxy and stub classes for you. Enable it in Gradle with buildFeatures { aidl = true }, then write src/main/aidl/com/example/IPlayer.aidl:

AIDL
// read-only example: IPlayer.aidl
package com.example;

import com.example.Track;           // a Parcelable declared in Track.aidl

interface IPlayer {
    void play(in Track track);          // blocks until the service returns
    int  volume();
    oneway void stop();                 // fire and forget
    List<Track> queue();
}

The service returns an implementation of the generated IPlayer.Stub from onBind():

Kotlin
// read-only example: needs Android
class PlayerService : Service() {
    private val binder = object : IPlayer.Stub() {
        override fun play(track: Track) { /* runs on a binder thread */ }
        override fun volume(): Int = 7
        override fun stop() { /* ... */ }
        override fun queue(): MutableList<Track> = mutableListOf()
    }
    override fun onBind(intent: Intent): IBinder = binder
}

On the client, IPlayer.Stub.asInterface(service) turns the binder you receive into a proxy; call it from a background thread because a plain call blocks.

Parcelable, direction tags and oneway

Only certain types cross a Binder: primitives, String, List and Map of allowed types, Bundle and anything that is Parcelable. With Kotlin, the kotlin-parcelize plugin does the work:

Kotlin
// read-only example: needs Android
@Parcelize
data class Track(val id: Long, val title: String, val seconds: Int) : Parcelable

You also write parcelable Track; in a Track.aidl so the AIDL compiler knows it. Non-primitive parameters need a direction tag: in (copied to the service), out (the service fills a new object) or inout. Use in unless you have a reason; it copies the least.

A method marked oneway returns immediately, with no result and no exception, and calls from one client are delivered in order. Use it for notifications such as "stop" where the client does not care about the outcome. Never mark something oneway and then expect a result.

An exported AIDL service is a public API of your app. Any app can try to bind to it. Protect it with a custom signature-level permission, check Binder.getCallingUid() inside methods, and never trust arguments. See Security on Android.

A marshalled call, simulated

The first stand-in models what the generated proxy and stub do. A Parcel is a flat list of values; the proxy writes arguments, "sends" the parcel, and the stub on the other side reads them back in the same order and calls the real implementation. The stand-in skips the kernel, but the flattening and the order-sensitivity are real.

Kotlin Proxy, Parcel and Stub (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

If the proxy wrote the fields in a different order than the stub reads them, the types would not line up and the call would fail. That is why generated code and @Parcelize matter: you should not write marshalling by hand.

A Messenger, simulated

The second stand-in shows the behavior that makes Messenger easy: many clients, one queue, one worker thread that handles one message at a time.

Kotlin One queue, one handler thread (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Calling native code: NDK, JNI and CMake

The second boundary is between Kotlin and C/C++. The NDK (Native Development Kit) provides compilers and headers for building native libraries (.so files) for each CPU architecture; JNI (Java Native Interface) is the glue that lets Kotlin and native code call each other. Typical reasons: reusing a C/C++ library, game engines, audio or image processing hot loops. It is not a way to make ordinary app code faster, and crashes in native code kill the whole process.

Install the NDK and CMake from the SDK Manager, add a CMakeLists.txt, and point Gradle at it:

Kotlin
// read-only example: needs Android
android {
    defaultConfig {
        externalNativeBuild { cmake { cppFlags += "-std=c++17" } }
        ndk { abiFilters += listOf("arm64-v8a", "x86_64") }
    }
    externalNativeBuild {
        cmake { path = file("src/main/cpp/CMakeLists.txt") }
    }
}
CMAKE
# read-only example: src/main/cpp/CMakeLists.txt
cmake_minimum_required(VERSION 3.22.1)
project("mathlib")
add_library(mathlib SHARED mathlib.cpp)
find_library(log-lib log)
target_link_libraries(mathlib ${log-lib})

In Kotlin, you load the library once and declare the function as external: the body lives in C++.

Kotlin
// read-only example: needs Android
object NativeMath {
    init { System.loadLibrary("mathlib") }      // loads libmathlib.so
    external fun dot(a: DoubleArray, b: DoubleArray): Double
}
C++
// read-only example: src/main/cpp/mathlib.cpp
#include <jni.h>

extern "C" JNIEXPORT jdouble JNICALL
Java_com_example_NativeMath_dot(JNIEnv* env, jobject /* this */,
                                jdoubleArray a, jdoubleArray b) {
    jsize n = env->GetArrayLength(a);
    jdouble* x = env->GetDoubleArrayElements(a, nullptr);
    jdouble* y = env->GetDoubleArrayElements(b, nullptr);
    double sum = 0;
    for (jsize i = 0; i < n; ++i) sum += x[i] * y[i];
    env->ReleaseDoubleArrayElements(a, x, JNI_ABORT);
    env->ReleaseDoubleArrayElements(b, y, JNI_ABORT);
    return sum;
}

The function name encodes the package, class and method (Java_ + package with underscores + _NativeMath_dot); a mismatch gives UnsatisfiedLinkError at the first call. Every Get...Elements needs a matching Release..., and each JNI crossing has a cost, so cross the boundary rarely with bigger chunks of work. Since Android 15 devices may use 16 KB memory pages, so rebuild native libraries with a current NDK (r28 aligns them by default) to remain compatible.

The C++ file is read-only here, but the C++ runner lets you try the loop itself: see C++ for Beginners for the language. Below is a Kotlin stand-in that models the cost model of the boundary: crossing it per element is slow, crossing once with a whole array is fast.

Kotlin The price of crossing the boundary (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Binder do when a client calls a method on an AIDL proxy?

    The proxy writes arguments to a Parcel, the driver delivers it, and the stub unmarshals it and calls the real implementation, then the reply returns the same way.
  2. 2. Your service needs a private API used only by your own app's activities. Which is the simplest correct choice?

    Within one process no marshalling is needed. A local Binder hands the activity a direct reference to the service.
  3. 3. What is the effect of marking an AIDL method oneway?

    A oneway call is asynchronous and cannot return a value. Calls from one client to the same service are still delivered in order.
  4. 4. A Messenger service handles messages from ten clients at once. How are they processed?

    A Messenger wraps a Handler, so messages are queued and processed serially. That is simple and thread-safe but less concurrent than AIDL.
  5. 5. Calling a JNI function throws UnsatisfiedLinkError. What is a likely cause?

    System.loadLibrary must load the .so, and the exported native symbol must match the class and method that declare the external function.

Summary

  • Android processes are isolated; Binder is the kernel-backed RPC that connects them, marshalling arguments through a Parcel.
  • Synchronous Binder calls block the caller and run on binder threads in the service; keep payloads small (about 1 MB shared buffer).
  • Choose the simplest bound-service style: a local Binder in one process, Messenger for serialized message passing, AIDL for a real multi-threaded cross-process API.
  • AIDL needs Parcelable for custom types, direction tags (in, out, inout) and oneway for fire-and-forget methods; exported services must be protected.
  • The NDK, CMake and JNI let Kotlin call C/C++ through external fun; cross the boundary rarely and release everything you acquire.
  • All IPC code here is read-only; the stand-ins model marshalling, queues and boundary costs.

Next: Play Console and Publishing