Android
Printing Labels from Android Using the Brother QL SDK
The Brother printer SDK documentation assumes a Java mindset. This post covers a production Kotlin integration for QL-series label printers over Wi-Fi, including bitmap generation, coroutine bridging, and Mutex-guarded print sessions.
- Published
- Reading
- 6 min
- Author
- Fidelis Uwem Joseph
Series · Part 4 of 5Android Foundations
- Three Retrofit Clients in One Android App with Hilt Qualifiers
- Encrypted Token Storage on Android with EncryptedSharedPreferences and Hilt
- Seeding a Room Database via ADB BroadcastReceiver in Kotlin
- Printing Labels from Android Using the Brother QL SDK
- Android Project Docs with MkDocs, Dokka, and Firebase Hosting
Brother QL-series printers are common in inventory and retail environments.
Their Android SDK exists, but the documentation is thin and the API is
callback-and-blocking — it was designed for Java on a background thread.
This post covers a production Kotlin integration: Wi-Fi discovery,
bitmap-based label generation, coroutine-safe printing with a Mutex,
and the suspendCancellableCoroutine bridge that makes the blocking
scanner API composable with the rest of a coroutines-first codebase.
Prerequisites
Android Studio Meerkat, Kotlin 2.0, coroutines 1.8.1, minSdk 23.
The Brother SDK .aar is distributed as a local library file, not through
Maven Central. implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar", "*.aar"))))
in your build.gradle.kts picks it up.
Background
The Brother SDK exposes a blocking PrinterDriverGenerator.openChannel() call
followed by printerDriver.printImage(). Both must run on a background thread.
The network scan API uses a callback that fires for each printer found and
returns a PrinterSearchResult when the scan window closes.
Neither API is coroutine-native. The path forward is withContext(Dispatchers.IO)
for the blocking calls and suspendCancellableCoroutine for the callback-based
scan. The other issue is concurrency: the SDK is not safe for concurrent print
sessions. A Mutex prevents two callers from opening the same Wi-Fi channel
simultaneously.
Implementation
1. Local library setup
dependencies { implementation( fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar", "*.aar"))) ) implementation(libs.coroutines.android)}Place the Brother SDK .aar in app/libs/. Sync the project and verify the
com.brother.sdk.lmprinter package is resolvable.
2. The Mutex guard
All print calls go through BrotherPrinters, an object singleton. The
Mutex is the only shared state. It ensures only one coroutine enters the
print path at a time, regardless of how many ViewModels or screens call into
the object.
object BrotherPrinters {
private val mutex = Mutex()
suspend fun printLabel( context: Context, colorName: String, partNumber: String, newOrUsed: String, ipAddress: String, printerModel: PrinterModel = PrinterModel.QL_710W, printerLabelSize: QLPrintSettings.LabelSize = QLPrintSettings.LabelSize.RollW38 ): Result<Unit> = withContext(Dispatchers.IO) { mutex.withLock { // ... print logic } }}mutex.withLock inside withContext(Dispatchers.IO) means the lock is held on
an IO thread. The coroutine that loses the lock suspends, not blocks — the IO
thread is released until the lock is available.
3. Text-to-bitmap label generation
The SDK prints a Bitmap, not text. You generate the bitmap yourself, which
gives you full control over layout, font, and label size.
private const val PRINTER_DPI = 300 // QL-700 series print head resolution
private fun textToBitmap( topText: String, bottomText: String, widthMm: Float = 38f, heightMm: Float = 10f, textColor: Int = Color.BLACK): Bitmap { val dpi = PRINTER_DPI val widthPx = (widthMm / 25.4f * dpi).toInt() val heightPx = (heightMm / 25.4f * dpi).toInt()
val bitmap = Bitmap.createBitmap(widthPx, heightPx, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) canvas.drawColor(Color.WHITE)
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = textColor textAlign = Paint.Align.LEFT typeface = Typeface.DEFAULT_BOLD }
// Shrink font until the longest string fits within 90% of label width val maxWidthText = if (topText.length > bottomText.length) topText else bottomText var textSize = heightPx / 2f paint.textSize = textSize while (paint.measureText(maxWidthText) > widthPx * 0.9) { textSize *= 0.9f paint.textSize = textSize }
val topTextHeight = abs(paint.ascent()) * 0.8f val xTopText = (widthPx - paint.measureText(topText)) / 2 val xBottomText = (widthPx - paint.measureText(bottomText)) / 2 val bottomBaseline = heightPx - paint.descent() * 0.2f
canvas.drawText(topText, xTopText, topTextHeight, paint) canvas.drawText(bottomText, xBottomText, bottomBaseline, paint)
return bitmap}4. Opening a channel and printing
mutex.withLock { val dir = File(context.filesDir, "brickwork") val channel = Channel.newWifiChannel(ipAddress) val result = PrinterDriverGenerator.openChannel(channel)
if (result.error.code != OpenChannelError.ErrorCode.NoError) { return@withLock Result.failure(PrinterException("Open channel: ${result.error.code}")) }
val printerDriver = result.driver try { val printSettings = QLPrintSettings(printerModel).apply { labelSize = printerLabelSize isAutoCut = true workPath = dir.toString() }
val bitmap = textToBitmap( topText = colorName, bottomText = "$partNumber [$newOrUsed]" )
val printError: PrintError = printerDriver.printImage(bitmap, printSettings) bitmap.recycle()
if (printError.code == PrintError.ErrorCode.NoError) Result.success(Unit) else Result.failure(PrinterException("Print: ${printError.code}")) } catch (e: Exception) { Timber.e(e) Result.failure(e) } finally { printerDriver.closeChannel() }}Every failure path returns Result.failure with the SDK’s error code. An
earlier version only logged the open-channel error and carried on, which
crashed on the null driver, and logged print errors but still returned
success — so the UI said “printed” when the printer was out of labels.
workPath must point to a directory the app owns. The SDK writes temporary
raster files there during the print job. Passing context.cacheDir also works
but is cleared more aggressively by the system.
5. Wi-Fi printer discovery
startNetworkSearch blocks for the whole search window (15 seconds here),
fires a callback for each printer it finds, and returns a
PrinterSearchResult at the end. Because it blocks, wrapping it directly in
withContext(Dispatchers.IO) would make the scan uncancellable: leaving the
screen would still hold a thread for 15 seconds. Instead, run it on an
executor and bridge it with suspendCancellableCoroutine, so cancellation
can call the SDK’s cancelNetworkSearch().
suspend fun scanWifiPrinter( context: Context, onFound: (Channel) -> Unit = {},): PrinterSearchResult = suspendCancellableCoroutine { continuation -> val option = NetworkSearchOption(15.0, false) continuation.invokeOnCancellation { PrinterSearcher.cancelNetworkSearch() }
Dispatchers.IO.asExecutor().execute { try { val result = PrinterSearcher.startNetworkSearch(context, option) { channel -> Timber.d("Found ${channel.extraInfo[Channel.ExtraInfoKey.ModelName]} at ${channel.channelInfo}") onFound(channel) } continuation.resume(result) // ignored if already cancelled } catch (e: Exception) { continuation.resumeWithException(e) } }}onFound fires during the scan window and is the right place to feed a
discovery list in the UI as printers appear. The function itself returns when
the window closes, or immediately if the calling coroutine is cancelled.
Testing
Connect a QL-710W to the local Wi-Fi network and run the scan:
val result = BrotherPrinters.scanWifiPrinter(context)// result.printers contains the discovered Channel instancesFor print verification, submit a test label and confirm auto-cut fires at the
end of the job. The SDK returns PrintError.ErrorCode.NoError on success.
Pitfalls
Production considerations
The 15-second scan window in NetworkSearchOption(15.0, false) is appropriate
for a local network with one or two printers; the second argument enables
tethering mode for printers joined to the phone’s own hotspot. Because results
stream through onFound, the UI can show printers as they appear and let the
user pick one before the window closes, then cancel the rest of the scan.
If the IP address changes between sessions (DHCP), store the printer model and
display name from Channel.ExtraInfoKey.ModelName in settings alongside the IP.
Show the user the model name in the UI so they can re-scan when the IP changes
rather than silently failing to connect.
Wrapping up
You now have a coroutine-native wrapper around the Brother SDK: Wi-Fi discovery
via suspendCancellableCoroutine, DPI-aware bitmap label generation, and
Mutex-guarded print sessions that prevent channel collisions under concurrent
use. The full implementation lives in BrotherPrinters.kt.
The next integration point is the settings screen where the user enters the
printer IP and selects label size — the stored values flow directly into the
printLabel call above.
Going deeper
Print crisp text, not grey mush. Thermal printers are one bit per dot.
The SDK converts your ARGB bitmap to black and white, and its default halftone
(error diffusion) is designed for photos: anti-aliased text edges become
speckled. For labels, set halftone = PrintImageSettings.Halftone.Threshold
(with a mid threshold) and draw the text without anti-aliasing. Barcodes in
particular need hard edges to scan reliably.
Check status before you print. printerDriver.getPrinterStatus() reports
cover open, no media and wrong media before a job is sent. Checking it first
turns “print failed: error 23” into “load 38 mm labels”, which is what a
person in a stockroom needs to see.
Queue jobs, don’t just lock them. The Mutex serialises calls, but a
user scanning twenty parts quickly still creates twenty suspended coroutines,
each with its own UI state. A Channel<PrintJob> consumed by a single
long-lived printing coroutine gives you a visible queue, retry of the head
job after the user fixes the printer, and a place to batch several labels into
one printImage call over a single channel.
Wi-Fi printers move. DHCP leases change. Storing the printer’s MAC or
serial number from extraInfo alongside its IP lets the app quietly rescan
and reconnect when the old IP stops answering, instead of asking the user to
re-enter it.