Why putting a Bitmap in your Bundle crashes only on some devices.
You ship a feature. It passes QA on three phones. Two weeks later, Crashlytics lights up with TransactionTooLargeException, concentrated on a handful of high-density devices and a particular OS release. The stack trace points into framework code you have never touched. Nobody on the team can reproduce it.
Nearly every time this happens, the cause is the same: the app pushed more data through a very small, very shared pipe than it was designed to carry. That pipe is Binder, and startActivity, getSystemService, ContentResolver.query, and half the framework calls you make before lunch all travel through it.
This post is about the mental model that makes those failures predictable: what Binder is, why its limits exist, how the limits bite, and how to design around them.
1. Why Android isolates processes, and why that demands a fast IPC
Every app runs in its own Linux process under its own UID. That isolation is the foundation of the Android security model: a buggy or hostile app cannot read your memory, and a crash in one app does not take down the others.
Isolation has a cost. Your app cannot directly call the code that starts activities, grants permissions, manages windows, or reads contacts. That code lives in system_server or in another app's process. Every one of those interactions is a cross-process call.
Classic Unix IPC (sockets, pipes, System V shared memory) did not fit well here:
- Sockets and pipes copy data twice (sender → kernel → receiver) and carry no built-in notion of caller identity.
- Shared memory is fast but has no access control or lifecycle story by itself.
- Android needed caller identity (who is asking, with which UID and permissions?), object references that can be passed between processes, and thread management for incoming calls.
Binder, a kernel driver at /dev/binder, gives the platform all three. It copies payload data once (from sender user space into the receiver's mapped buffer), stamps every transaction with the caller's UID and PID so services can enforce permissions, and routes the call to a thread in the target process's thread pool.
The practical consequence: a “simple” framework call is an RPC. It serializes arguments, switches processes, waits for a thread in another process, and deserializes a reply. That is usually microseconds to a few milliseconds. Occasionally it is much longer, and that “occasionally” is where this post lives.
2. Binder in one picture
Read the picture left to right:
- Your code calls what looks like an ordinary method on an interface.
- The proxy (generated from AIDL, or hand-written inside the framework) flattens the arguments into a
Parcel. - The kernel driver copies the parcel into the target process’s Binder buffer and wakes a thread there.
- The stub unflattens the parcel in
onTransact(), calls the real implementation, and writes the reply. - The reply travels back, and the caller thread, which has been blocked the entire time, resumes.
Two details from that picture drive everything below: the buffer in step 3 is finite, and the blocking in step 5 happens on whichever thread you called from.
Here is how that looks from the Kotlin side. This is the AIDL you would write for a bound service:
// IThumbnailService.aidl
// interface IThumbnailService {
// String describe(long photoId);
// }
class ThumbnailClient(context: Context) {
// Application context: a long-lived client must not pin an Activity.
private val context = context.applicationContext
private var service: IThumbnailService? = null
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
service = IThumbnailService.Stub.asInterface(binder) // proxy if remote
}
override fun onServiceDisconnected(name: ComponentName) { service = null }
}
fun bind() = context.bindService(
Intent(context, ThumbnailService::class.java),
connection,
Context.BIND_AUTO_CREATE,
)
// Pair every bind with an unbind (e.g. from onStop/onDestroy), or the framework
// logs ServiceConnectionLeaked and the connection outlives its owner.
fun unbind() {
service = null
context.unbindService(connection)
}
// Looks like a normal call. It is an RPC and it blocks the caller.
fun describe(photoId: Long): String? = service?.describe(photoId)
}
The call site gives no hint that it can block, throw RemoteException, or hit a size limit. That invisibility is the root of most Binder bugs.
3. The shared transaction buffer
Each process that uses Binder gets a fixed region of memory for incoming transaction data. On Android it is a little under 1 MB (1 MB minus two pages). The detail most people miss: this is one budget per process, shared by every transaction in flight, not a per-call allowance.
That has several implications:
- A single 600 KB payload is survivable on its own. Two concurrent 600 KB payloads are not.
- Space is held until the receiver is finished with the transaction, so slow receivers keep the buffer occupied longer.
- Your process is not the only one that matters. When you send data to
system_server, you consume space in its buffer, and it is serving every app on the device. -
oneway(asynchronous) transactions are limited to roughly half of the buffer, so they hit the ceiling sooner.
When the driver cannot satisfy an allocation, the call fails and the framework surfaces it as TransactionTooLargeException (or, for some paths, a DeadObjectException / RuntimeException wrapping it).
You can make the shape of this budget visible during development. This helper measures what a Bundle would cost if marshalled:
import android.os.Bundle
import android.os.Parcel
fun Bundle.marshalledSizeBytes(): Int {
val parcel = Parcel.obtain()
return try {
parcel.writeBundle(this)
parcel.dataSize()
} finally {
parcel.recycle()
}
}
/** Per-key cost (total minus total-without-key), biggest first. Debug builds only. */
fun Bundle.debugSizeReport(): String {
val total = marshalledSizeBytes()
return keySet()
.map { key -> key to total - Bundle(this).apply { remove(key) }.marshalledSizeBytes() }
.sortedByDescending { it.second }
.joinToString("\n") { (key, size) -> "%-30s %,10d B".format(key, size) }
}
Wire it into a debug-only lifecycle callback and you get an early warning long before production does:
class SaveStateWatchdog : Application.ActivityLifecycleCallbacks {
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
val size = outState.marshalledSizeBytes()
if (size > 100 * 1024) { // 100 KB is already suspicious
Log.w("BinderBudget", "${activity::class.simpleName} saved $size B\n${outState.debugSizeReport()}")
}
}
// other callbacks omitted
override fun onActivityCreated(a: Activity, s: Bundle?) = Unit
override fun onActivityStarted(a: Activity) = Unit
override fun onActivityResumed(a: Activity) = Unit
override fun onActivityPaused(a: Activity) = Unit
override fun onActivityStopped(a: Activity) = Unit
override fun onActivityDestroyed(a: Activity) = Unit
}
4. TransactionTooLargeException: what actually causes it
Cause 1: onSaveInstanceState and everything stuffed into it
When your activity goes to the background, the framework saves its state, and that state (every Bundle from your activity, its fragments, and every view with an ID) is sent to system_server over Binder so it can survive process death. Since Android 7.0 (API 24), a failure here crashes the app when the activity stops, which is why users see the crash when they leave a screen rather than when they open it.
The total is the sum of everything in that state: view hierarchy state, fragment arguments, fragment saved state, and whatever you added by hand. Teams that diligently trim their own Bundle still overflow because a RecyclerView adapter, a ViewPager, or a third-party library quietly contributes its own.
Cause 2: large Intent extras
An Intent is also marshalled into a parcel and sent through Binder to system_server (for startActivity) and then on to the target. The same budget applies:
// Looks harmless. Is a time bomb.
startActivity(
Intent(this, ViewerActivity::class.java)
.putExtra("photo", hugeBitmap) // pixel data in the parcel
.putExtra("results", allSearchResults) // ArrayList<Parcelable> of 5,000 items
)
Cause 3: large replies and cursors
The reply is a transaction too. A ContentProvider returning a big Bundle, an AIDL method returning List<Item>, or a bulk applyBatch can overflow the caller's buffer. (Cursor rows are transferred through shared memory windows rather than the parcel, which is why cursors usually scale better than returning lists, though a very large single row can still cause trouble.)
So why does the Bitmap crash only on some devices?
Because the size of a Bitmap is not a property of your code. It is a property of the device:
- Decoded size follows density. A drawable decoded without explicit target dimensions is scaled by screen density. The same resource that is a few hundred KB on a mid-density test phone can be several times larger on an xxhdpi or xxxhdpi device.
-
Pixel format and OS version matter.
ARGB_8888is 4 bytes per pixel. On newer releases, large bitmaps may be written to a parcel through shared memory (a file descriptor) instead of inline bytes, but that depends on the OS version, on whether the parcel allows file descriptors, and on the bitmap itself. Older releases, or paths that copy pixels inline, put the full pixel data in the shared Binder buffer. So a payload that squeaks by on one release or code path can overflow on another, and you should never rely on the shared-memory path to save you. - The rest of the state varies too. Different devices restore different fragment stacks, have different font and display scales, and run different OEM-modified UI components, so the “everything else” in the buffer is not constant either.
- The buffer is shared. The call that fails is the one that happened to arrive when the budget was nearly spent. That is a timing property, not a size property.
Your emulator and your two Pixels sit comfortably below the line. A customer’s tablet is a pixel density bucket above it. Same code, different bytes.
The Bitmap is the memorable example, but the principle is general: any payload whose size depends on user data, screen size, or content is a latent crash.
How to avoid it
Do not try to find the “safe” size. There is no portable one, because the budget is shared and you do not control the other tenants. Change what you pass instead.
Save identifiers and small primitives, and restore heavy state from a durable source:
// Item and SearchRepository stand in for your own types.
@OptIn(ExperimentalCoroutinesApi::class) // flatMapLatest is still experimental
class SearchViewModel(
private val savedState: SavedStateHandle,
private val repository: SearchRepository,
) : ViewModel() {
// A few bytes survive process death.
private val queryId: StateFlow<Long?> =
savedState.getStateFlow(KEY_QUERY_ID, null)
val results: StateFlow<List<Item>> = queryId
.filterNotNull()
.flatMapLatest { id -> repository.observeResults(id) } // heavy data comes from Room
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
fun onSearch(text: String) {
viewModelScope.launch {
savedState[KEY_QUERY_ID] = repository.runSearch(text) // returns the persisted query ID
}
}
private companion object { const val KEY_QUERY_ID = "query_id" }
}
For the Intent, pass the key to the data:
// Producer
val photoId = photoRepository.saveCapture(bitmap) // writes to disk or a DB
startActivity(ViewerActivity.intent(this, photoId))
// Consumer
class ViewerActivity : ComponentActivity() {
private val photoId: Long by lazy { intent.getLongExtra(EXTRA_PHOTO_ID, -1L) }
companion object {
private const val EXTRA_PHOTO_ID = "photo_id"
fun intent(context: Context, photoId: Long) =
Intent(context, ViewerActivity::class.java).putExtra(EXTRA_PHOTO_ID, photoId)
}
}
When you genuinely must share bytes across processes, use a mechanism designed for bulk data: a ContentProvider file URI opened with ParcelFileDescriptor, SharedMemory, or MemoryFile. Binder then carries a small handle while the data travels through memory the kernel maps for both sides.
5. Synchronous calls versus oneway
By default, a Binder call is synchronous: the calling thread blocks until the server replies. In AIDL, marking a method (or a whole interface) oneway changes the contract:
// ITelemetry.aidl
// oneway interface ITelemetry {
// void record(in String event);
// }
What oneway gives you and what it takes away:
-
Caller blocking: a synchronous call blocks until the reply arrives;
onewayblocks only until the transaction is queued. -
Return value: synchronous calls can return data;
onewaymethods must returnvoid. -
Server exceptions: they propagate back to a synchronous caller; with
onewaythey never reach you. -
Ordering:
onewaycalls to the same target object are delivered serially, in queue order. -
Buffer budget: synchronous calls can use the full shared buffer;
onewaygets roughly half of it.
Two failure modes follow from that last row:
-
onewayis not free. If the server is slow, queued async transactions pile up in its buffer. A flood of smallonewaycalls (high-frequency telemetry, per-frame callbacks) can fill the async space and start failing, and the failure is easy to miss because there is no reply to carry an error back. -
Callbacks are
onewayin disguise. When the system calls yourIBindercallback from another process, that direction is oftenoneway. Doing heavy work on the binder thread that receives it, or being slow to return, backs up the sender.
Practical rule: use oneway for notifications where losing one is acceptable and ordering within a single object is sufficient. Do not use it as a way to hide a slow call.
6. How a main-thread Binder call becomes jank or an ANR
The caller thread blocks for the duration of a synchronous call. If that thread is your main thread, the UI cannot draw, handle input, or run a single message while it waits.
The server side is not guaranteed to be quick. A call into system_server may wait for:
- a lock held by some other system operation,
- a free binder thread (the pool is bounded; a busy service can be saturated),
- a downstream call that itself goes to another process (Binder chains),
- the device being under memory or I/O pressure, which makes everything slower at once.
So a call that takes 200 µs on your desk can take 300 ms on a loaded low-end phone at 2 a.m. That is dropped frames at the mild end. If the main thread is blocked long enough, the system’s input dispatch timeout (about five seconds) fires and the user sees “App isn’t responding”.
The calls that surprise people are the ones that look like property access:
// All of these can cross a process boundary on the main thread:
val pm = context.packageManager
val apps = pm.getInstalledApplications(0) // large reply, system_server lookup
// On API 30+ this only returns packages visible to you: declare <queries> or
// QUERY_ALL_PACKAGES, otherwise the list is a filtered subset.
val cr = context.contentResolver
val cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null) // another app's process
val caps = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) // system service calls
getSystemService itself is mostly a local cache lookup. The method calls on the returned manager are the RPCs.
Keep them off the main thread, and make the policy enforceable:
class AppDispatchers(
val io: CoroutineDispatcher = Dispatchers.IO,
)
class InstalledAppsRepository(
private val packageManager: PackageManager,
private val dispatchers: AppDispatchers,
) {
suspend fun installedPackages(): List<PackageInfo> = withContext(dispatchers.io) {
packageManager.getInstalledPackages(0) // blocks this IO thread, not the UI
}
}
Be aware of one limit: withContext moves the blocking off the main thread, but it cannot interrupt a Binder call already in progress. If the coroutine is cancelled, that IO thread stays tied up until system_server replies, so avoid launching bursts of such calls and prefer fewer, batched ones.
StrictMode helps in debug builds, with a caveat: detectAll() flags disk and network access on the main thread, but it does not flag arbitrary Binder calls. A PackageManager or ContentResolver call is only caught if it happens to touch disk or network on your thread, or if you wrap it yourself with StrictMode.noteSlowCall("name") after enabling detectCustomSlowCalls() (included in detectAll()). For Binder visibility proper, use a trace (next section).
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build()
)
}
One more subtlety: moving the call to a background thread removes the jank but does not make the call free. It still occupies a Binder thread in the service and still counts against the buffer. A loop of 500 background query calls is still 500 transactions.
7. Practical: finding Binder calls in a trace
Theory is cheap. To see which Binder calls your app actually makes, record a system trace and read it. (This builds on the capture setup from the profiling series: see [Recording a Perfetto trace] and [Reading the main thread timeline].)
A workable procedure:
-
Record a Perfetto trace with the
binder_driver,sched,freq, andviewcategories enabled, while you reproduce the slow interaction. - Find your main thread (the thread named after your package, whose TID equals the PID) and zoom into a janky frame or a long gap.
-
Look for
binder transactionslices on the main thread's track. These are your outgoing synchronous calls. The slice duration is how long the caller waited. -
Follow the flow arrow to the matching
binder replyslice on aBinder:<pid>_Nthread in the other process. If the reply slice is short but the transaction slice is long, the time was spent waiting to be scheduled or to get a binder thread. If the reply is itself long, the server was doing slow work, and the slices beneath it tell you what. - Check the thread state under the transaction slice. A thread parked while waiting for the reply shows as sleeping, with a wakeup from the server-side thread. If you see long Runnable time instead, the CPU was contended.
- Use the Perfetto SQL to rank offenders instead of scrolling:
INCLUDE PERFETTO MODULE android.binder;
-- Longest binder transactions initiated by your process's main thread
SELECT
client_ts AS ts,
client_dur / 1e6 AS ms,
client_process,
server_process,
aidl_name,
method_name
FROM android_binder_txns
WHERE client_process LIKE 'com.example.app%'
AND is_main_thread = 1
ORDER BY client_dur DESC
LIMIT 20;
android_binder_txns lives in the Perfetto standard library, so the INCLUDE PERFETTO MODULE line is required, and the columns may differ slightly between Perfetto versions. The aidl_name / method_name values are only populated when the trace contains AIDL annotations, which depends on the OS version and trace config. When they are missing, the server process name and the slice names under the reply usually identify the call well enough.
Pair this with a quick look at what you are sending: the marshalledSizeBytes() helper from earlier tells you the payload side of the story that the trace only shows as duration.
8. Guidelines: pass IDs, not payloads
If you remember one thing, make it the picture above. The checklist version:
- Treat every framework call on a manager object as an RPC. It blocks, it can fail, it can be slow.
-
Never block the main thread on one when you can avoid it. Wrap the call in
withContext(Dispatchers.IO)and keep StrictMode on in debug (it will not catch every Binder call; traces will). -
Pass identifiers and small primitives in
Intentextras, fragment arguments, and saved state. Reload heavy data from Room, a file, or a repository. -
Never put a
Bitmap, a list of models, or raw JSON in aBundle. If you cannot bound its size, it does not belong there. - Budget your whole saved state, not just your part of it. Log its marshalled size in debug builds and alert at about 100 KB.
-
Use bulk-capable mechanisms for bulk data (file descriptors, shared memory,
ContentProviderfiles). -
Be sparing with
oneway. It is a notification channel, not a way to make a slow call fast. - Test on the extremes: the highest-density device, a low-memory device, and an older OS you still support. Binder failures concentrate where the numbers are largest.
- Instrument first, guess second. A Perfetto trace shows who waited on whom; a size log shows who is hogging the buffer.
Binder is one of the best-engineered pieces of Android, and its limits are not bugs; they are the price of a fast, secure, uniform way for isolated processes to talk. Once you read your code as a series of toll-booth crossings, with a lane count that is shared with everyone else, the crashes that “only happen on some devices” start to look a lot less mysterious.
🔐 Go Beyond Using Android — Master How It’s Actually Secured
If you’re building, testing, or breaking Android apps, understanding the security model beneath the SDK separates developers who follow best practices from those who truly understand why those practices exist. I highly recommend “Mastering Android Security: From Fundamentals to Advanced Practice.” It’s a comprehensive, architecture-first journey through app sandboxing, cryptography, network defense, reverse engineering, and exploitation — spanning everything from AndroidManifest.xml internals to TrustZone and the Verified Boot chain, with hands-on labs at every step.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover
Originally published on Medium.





Top comments (0)