Topics
Recent articles

Android & Mobile

How to Queue Android Bluetooth Print Jobs Without Duplicate Receipts

Build an Android receipt queue that deduplicates taps, retries pre-write connection failures, and requires review after an uncertain send.

Table of Contents9 sections
Pixel art diagram: retry if no receipt write was attempted, and review once a write was attempted.
The first attempted receipt write is the boundary for automatic retries.

A Bluetooth connection drops just after an Android app sends a receipt. The printer might have produced a complete slip, a partial slip, or nothing. Treating all three outcomes as a reason to retry is how one sale gets two originals.

Quick solution:

Persist one job per receipt intent in Room. Retry automatically only when the app knows it never attempted a receipt write. Persist a sending marker before writing, and show an explicit review action if the outcome becomes uncertain.

Connect failed before first write → back off and retry
Write attempted, outcome unknown → review; never auto-resend
Operator requests another slip → new job marked COPY

Choose what your app can actually promise

There are two kinds of duplicate to prevent. A double tap can create two database rows for the same original, so the first problem is duplicate enqueue. A retry after a lost connection can send the same row twice, so the second is duplicate delivery. Fixing either problem on its own does not fix the other. A perfectly unique Room row can still cause two physical prints. A careful Bluetooth sender can still print two originals if it accepted two job rows for one tap.

For an ordinary stream-based printer, aim for one locally recorded original intent and no automatic replay of an attempt that could already have reached the printer. This deliberately favors avoiding a duplicate over automatically recovering every missing slip. Only claim stronger guarantees if the particular printer protocol documents a durable job identifier, a way to check that identifier after reconnecting, and the exact event that the status represents. A status for being online, having paper, or accepting bytes is not an acknowledgment of a particular receipt.

If you still need to implement socket connection, receipt layout, or byte formatting, start with the Android Bluetooth receipt printer integration guide. The queue discussed here sits above that layer. Its job is to decide which immutable payload should be offered to the transport, whether it may be sent again, and what the operator should see if the answer is unclear.

Give the original and each copy different identities

Suppose a fictional checkout with ID S204 needs one original customer receipt. Use a stable key such as sale:S204:original:customer. Generate it from the business action rather than from the click, current time, or a random value generated on every call. Decide which roles count as distinct intended slips. A merchant slip and a customer slip can have different keys; switching printers for the same customer original should not create a different original key.

Store the destination separately. An explicit copy can instead have a key such as sale:S204:copy:C17, where C17 identifies one deliberate copy request and is reused if that request is submitted twice. Keep the sale record unchanged. The copy operation creates a new queue entry, not a second sale, not an update that erases the original attempt, and not an automatic consequence of a timeout. Make the copy label part of the rendered payload, not just a label in the app.

Save an immutable render snapshot or a reference to immutable data with a known rendering version. Do not rebuild a pending original from a mutable shopping cart. After a process restart, the item prices or the receipt footer may have changed. If the payload is stored outside Room, make sure the bytes are durable before publishing a row that references them, and define a cleanup policy for orphaned files. Avoid putting raw receipt contents into worker inputs or logs; make the worker read the job by ID.

Enforce deduplication and claiming in Room

Add a database-enforced unique index over the intent key, with a non-null key for every job. Returning the existing job for a repeated request lets two views converge on the same status. A UI button that disables after a tap helps the person, but it is not a concurrency control: a state restoration handler, a second screen, or an event replay can bypass it. The Room entity guide shows how to declare unique indices.

Use a short Room transaction to insert or retrieve the intent and, when relevant, commit it with the local sale event. A worker also needs a conditional claim so that two callbacks cannot both decide they own the same row. Here is the SQL shape for one transition. The worker proceeds only if the update affects exactly one row; two contenders using different attempt tokens cannot both win the same transition from QUEUED.

CREATE UNIQUE INDEX print_job_intent_key ON print_job(intent_key);

UPDATE print_job
SET state = 'CONNECTING', attempt_token = :token
WHERE id = :jobId
  AND state = 'QUEUED'
  AND eligible_at_ms <= :nowMs;

Make later updates conditional on both the expected state and the attempt token. If a stale callback arrives after the row has changed owners or moved to review, its update must do nothing. If a row is assigned to a different destination before sending, change the assignment while it is still queued, not while the old driver may be using the socket. Keep the database transactions short: do not hold one open across a slow connection, output-stream write, or operator decision. None of those operations can roll back along with the database.

Mark the boundary before the first receipt byte

Use CONNECTING for operations that do not attempt to write any part of the payload, then commit SENDING before making the first receipt write. Treat the entire operation that can submit bytes as the boundary. If your printer SDK bundles connection and printing together, move to SENDING before calling it unless it exposes and documents a way to know that it failed without submitting anything. The queue cannot infer that guarantee from the wording of an exception.

After a failed connection, a retry is safe for duplicate prevention only if the original attempt never got as far as writing receipt bytes. A write that throws might have sent a prefix. A write that returns might have handed bytes to a buffer while the mechanism still has paper to move. BluetoothSocket exposes streams, and Java’s OutputStream contract describes writes and flushing in terms of bytes and their destination, not completion of a physical receipt. As an engineering inference from those interfaces, a returned write or flush does not by itself establish that the slip emerged.

QUEUED → CONNECTING → SENDING → SENT_UNCONFIRMED
              │          └──→ NEEDS_REVIEW
              └──→ QUEUED (no receipt write attempted; backoff)

SENT_UNCONFIRMED records that the app’s transport path returned without reporting an error and that automatic sending is done. Show something like “Sent to printer” rather than “Printed” unless you have documented confirmation or a human checked. NEEDS_REVIEW is for losses or exceptions that leave the result unknown. A crash after committing SENDING but before the actual write can send a job to review unnecessarily; that is the deliberate cost of committing the marker before the action that cannot be rolled back. Writing first creates the worse case in which printed output can exist but the queue still looks safe to retry.

Schedule a drain without making the scheduler the queue

Use Room as the durable queue and use a worker to drain it. WorkManager unique work can limit scheduler work with the same name according to its conflict policy. It does not enforce uniqueness of receipt business intents, and it does not protect a socket that another code path opens directly. Route every sender through one dispatcher per physical printer. A per-job claim alone does not stop two different jobs from sending to the same printer at once.

One practical setup is to run a single queue drain at a time for each printer within one app installation. If multiple phones send to the same printer, Room and a local unique work name do not coordinate across devices. Decide whether only one phone owns that printer, or whether a shared system assigns work. Even a shared dispatcher does not give a stream printer durable job deduplication. Keep the scope clear before promising receipt uniqueness across a store.

Account for the gap between committing a job and scheduling a drain. The app could be killed in that gap, or a request to enqueue unique work with KEEP could be ignored while the current drain is about to exit. Arrange a recovery scan when the app opens or reconnects and, if unattended recovery is required, use a suitable scheduled reconciliation to look for stranded rows. Use work as a wake-up hint rather than proof of delivery. Apply bounded backoff to pre-write failures and surface a clear reason when human action is required, such as resolving a pairing or permissions problem. Do not translate every exception into WorkManager retry; first persist what happened to the specific receipt.

Recover dead attempts without letting two writers overlap

A process may disappear while the database is in any state. Leftover QUEUED jobs can be attempted later. A leftover CONNECTING row can be requeued after confirming that its owner cannot subsequently reach the first write. A leftover SENDING row goes to review once recovery has established the old attempt is abandoned. Never make an old SENDING row sendable again simply because ten seconds elapsed. A slow but still-running write is not evidence that nothing reached the printer.

Design for ownership separately from timeouts. Within a single process, serialize the drain and close a timed-out connection before allowing another job to use that printer path. If an in-flight write cannot be stopped with a defined guarantee, don’t let a second worker race it. If ownership can be superseded, a worker must win the conditional transition to SENDING with its current token before using the stream. Tokens prevent stale updates to Room; they cannot revoke bytes already written to a socket. A distributed lease by itself is not a fence that a raw printer understands.

For strict ordering, consider holding the next job for the same device until an ambiguous attempt is reconciled. Some queues instead allow later unrelated jobs when the transport has been closed and the driver can safely reinitialize the printer according to its documentation. That choice affects an operator’s ability to match slips to sales. Decide the policy before a disconnection happens, and do not assume that reopening a connection clears partial output or resets the hardware’s formatting state.

Work through one disconnect and one intentional copy

In the example checkout, the operator taps twice. Both calls choose sale:S204:original:customer; Room returns one job. An initial connection fails before any receipt bytes are attempted, so the job is eligible for a delayed retry. The next attempt connects, commits SENDING with a new token, and starts writing. The printer loses connection during the attempt. The worker persists NEEDS_REVIEW and stops automatic sends for that job. For the same failure, an app that simply calls Result.retry could print another complete original after an already printed receipt.

The UI can display “Check printer for receipt S204” and offer “Mark as printed” or “Print copy.” If a good slip exists, recording an operator confirmation is enough. If there’s only a strip or nothing came out, the operator may request a copy. That new job preserves the original receipt reference and uses a separate copy intent. Repeated taps on the same copy request should resolve to the same copy job, just as original taps do. Whether a copy needs a disclosure or a particular label depends on your product’s requirements; the important technical property is that the action is visible and deliberate.

Record the attempt token, state transitions, transport outcome category, and timestamps. That timeline can answer which phase failed without revealing the customer, payment information, or receipt contents. Look at how many ambiguous attempts need review and what proportion are resolved by finding a complete slip. Those are useful measures for deciding whether a simpler transport is good enough or whether investing in a printer with documented per-job tracking would actually reduce work at the counter.

Test the point between database state and physical output

A test that prints one happy-path receipt does not exercise the retry boundary. First give the dispatcher a fake transport that can fail before a write, throw after receiving a prefix, return successfully, and stall until the owner is cancelled. Check the job state as well as how many times the transport was called. Assert that a second worker cannot obtain the same claim, and that a repeated enqueue doesn’t change the payload of an existing original. Restart the app with deliberately seeded rows representing a crash between steps.

Scenario Expected app outcome
Two original requests use the same key One row; both callers see the same job
Connect fails before any receipt write Job backs off; retry is allowed
Crash after committing SENDING No automatic resend; operator review
Write throws after accepting a prefix Operator review; no replay
Write returns with no printer-level acknowledgment Sent, not confirmed as printed
First drain exits while another job is queued Recovery scan finds the stranded job
Operator submits the same copy request twice One new COPY job

On the actual device, verify power loss, paper-out behavior, and reconnect with your supported printer models. Keep the fake tests for deterministic state transitions; hardware tests tell you where the printer really buffers, pauses, or resumes. For each test, count complete slips and inspect partial ones instead of counting only write calls or worker successes. If your field tests expose a different behavior across printer models, keep that distinction explicit in the adapter rather than broadening the guarantee in the generic queue.

Before shipping:

The strongest claim a typical app can make is not “we always print exactly once.” It is “we record the original once, never quietly replay an uncertain send, and give the operator a clear way to recover.”

You Might Also Like

View all articles