What startDiscovery() Actually Returns: Tracing Android Bluetooth Discovery to the Controller
Make a Bluetooth device search page. Tap "Start Discovery". startDiscovery() has already returned true, but the list is still empty. This return value tells the App that the service accepted the call. The devices on the page have to wait for subsequent ACTION_FOUND broadcasts to arrive. Separating REQUEST, STARTED, FOUND, and FINISHED in Logcat shows which stage signals the App received within the observation window.
13.1 Discover Devices with BluetoothAdapter
BluetoothManager.getAdapter() returns the public SDK entry for the local Bluetooth. Remote devices are represented by the BluetoothDevice in broadcasts. This example runs in the foreground and requires Android 13 (API 33) or higher. Turn on Bluetooth in system settings first and confirm the Adapter is available. The Manifest declares BLUETOOTH_SCAN and BLUETOOTH_CONNECT; the App requests the "nearby devices" permission when not yet granted.
Register the receiver first, then initiate discovery. The call order is excerpted below; the appendix contains null checks, permissions, result reading, and cleanup.
BluetoothManager manager = getSystemService(BluetoothManager.class);
BluetoothAdapter adapter = manager.getAdapter();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED);
boolean accepted = adapter.startDiscovery();
startDiscovery() returns whether this call was accepted. The EXTRA_DEVICE in ACTION_FOUND carries the device object, EXTRA_RSSI is optional. When ACTION_DISCOVERY_FINISHED is received, the local observation window is closed. For an active end or leaving the page, the example only attempts cancelDiscovery() on observation rounds that returned true, then unregisters the Receiver. Discovery is a shared operation; whether the system continues scanning depends on the conditions in 13.8.
The receiver uses RECEIVER_EXPORTED to receive protected system broadcasts sent by the Bluetooth process, handles only the three actions above, and checks the device extra. The example declares neverForLocation to indicate it does not infer physical location from Bluetooth results; some BLE beacons may be filtered.
Discovery, Pairing, and Connection
Classic Bluetooth BR/EDR uses Inquiry to find devices in discoverable mode. Low-energy Bluetooth LE scanning receives advertisements; the independent entry is BluetoothLeScanner. The startDiscovery() tracked in this chapter, on fixed versions, also requests an LE scan when the controller supports BLE, so the App's ACTION_FOUND may also come from LE. To claim a result comes from classic Inquiry, HCI events are needed.
Pairing negotiates authentication and keys. Bonding saves the pairing relationship. ACL is the controller link that carries upper-layer protocols. Profiles define how a class of business interconnects, e.g., A2DP audio, HID input, or PAN networking. GATT organizes data through services, characteristics, and ATT. Seeing a device, bond completion, ACL establishment, A2DP connection, and hearing audio each have their own evidence; 13.7 gives the lookup entry.
13.2 Observe a Discovery in Android Studio
- In Android Studio create a new
Empty Views Activity, choose Java, packagecom.example.btstudy, Minimum SDK 33. Keep the template's Gradle files, make sure the platform corresponding to the app module'scompileSdkis installed, andcompileSdkis at least 33. Replace the Manifest and MainActivity as per Appendix A, then sync Gradle. - In Device Manager create a Phone AVD, e.g., Pixel device configuration with Android 14 (API 34) Google APIs image, and choose a system image that matches your computer's architecture. After booting, check Bluetooth in Android settings. Select the AVD and click Run; Android Studio builds, installs, and launches the App.
- Open Logcat on the same AVD and filter with
package:com.example.btstudy tag:BtStudy. On the first tap of "Start a round of discovery", if the system asks, allow access to nearby devices, then tap again to start discovery. If already granted, one tap is enough. Keep the App in the foreground and watch the UI or Logcat. After a round completes, you can initiate another round and tap "End local observation and request cancel" within the observation window.
| What you see | What you can infer |
|---|---|
NO_ADAPTER, BLUETOOTH_OFF or permission prompt |
Check image capabilities, system Bluetooth switch, or nearby device authorization first. If prerequisites are not met, discovery has not been initiated in this example. |
REQUEST accepted=true |
The API accepted the call; a new discovery may start later, or an existing discovery may be shared. |
REQUEST accepted=false or REQUEST SecurityException |
The call was not accepted; this example ends local observation. Permissions, Adapter state, and service conditions are in 13.4. |
STARTED, FOUND address=…, FINISHED |
Respectively indicate observed start, device result, or discovery end broadcast. Broadcasts have no App-specific request ID. Results may come from a discovery other apps are also using; the end broadcast does not explain why. |
LOCAL_END reason=… |
The App has stopped observing. If no end broadcast is observed after about 25 seconds, the timer task attempts cancel and exits. Execution time depends on main-thread scheduling. |
You can first disable Bluetooth to confirm the button shows BLUETOOTH_OFF. Then re-enable Bluetooth, keep other conditions unchanged, and observe whether it reaches REQUEST. A regular AVD is used to observe App startup, authorization, API return, and actually received broadcasts. When the current image has no discoverable peer, you may receive FINISHED without any FOUND. To reliably reproduce classic discovery results, run the same App on an Android 13+ real device and prepare a device under your control that has entered classic Bluetooth discoverable mode. The addresses and device names in the experiment are only for local comparison. To prove a discovery result comes from classic Inquiry, match the address in HCI events to that round's log as per Appendix B.
From App to Controller
HCI (Host Controller Interface) defines the commands, events, and data between the Host protocol stack and the controller. JNI connects Java to Native code inside the Bluetooth process. The default AIDL HAL forms another Binder boundary, responsible for handing HCI packets to the selected transport backend.
Look at the Android layers and runtime locations in the architecture diagram. Apps use BluetoothAdapter to access the Bluetooth process; system_server manages service and proxy lifecycles. The default HAL can connect to the driver via the Linux HCI user channel, or fall back to a direct fd. Virtual controllers are endpoints that need separate verification.
The flowchart marks three stopping points. A call can be rejected, can reuse an existing discovery, or can generate a new Inquiry. Discovery results and end broadcasts then enter the App's observation window.
The overall sequence chooses a classic discovery initiated when idle, successfully receives a device, and ends naturally. The diagram shows local delivery, HCI events, and app main-thread consumption along the same set of lifelines. The controller may issue Inquiry Complete before the App receives FOUND; the diagram is only one interleaving. Early cancellation is expanded separately in the lower half of the same figure.
13.3 Review How the Adapter, Proxy, and Native Callbacks Are Established
Go back to the app process in the figure; first find the proxy already held when the App calls. The App obtains the BluetoothManager created by Context. Its constructor calls BluetoothAdapter.createAdapter(mContext); getAdapter() returns that field. createAdapter obtains IBluetoothManager from the BluetoothFrameworkInitializer's service manager, then constructs the Adapter. The Adapter constructor registers a process-level manager callback; the Binder returned by registerAdapter is wrapped into IBluetooth; service up/down callbacks update the business proxy. The manager lives in system_server; the real receiver of startDiscovery is in the Bluetooth process, not BluetoothManagerService replacing the protocol stack's search.
Source: packages/modules/Bluetooth/framework/java/android/bluetooth/BluetoothAdapter.java, lines 1026–1032. BluetoothAdapter.java fixed source.
mServiceLock.writeLock().lock();
try {
mService = registerBluetoothManagerCallback(mManagerCallback);
} finally {
mServiceLock.writeLock().unlock();
}
}
mService holds the current service proxy; AttributionSource holds call attribution information. Remote devices are not created from this Binder parameter; they are established from addresses in discovery events and the RemoteDevices cache.
Inside the Bluetooth process, AdapterService constructs new AdapterNativeInterface() by default and stores it as a final field. onCreate's initialization loads bluetooth_jni and calls mNativeInterface.init(...); init creates AdapterNativeCallback, later associating BondStateMachine and RemoteDevices. JNI registration saves the &bluetoothInterface function table; initNative makes GlobalRefs to NativeInterface and its callback. These references let Native call back the same set of Java objects when async results arrive; they do not move Java object memory into the controller. cleanupNative deletes global references after stack cleanup, and callback.cleanup clears its business associations, preventing use of a terminated service.
Source: packages/modules/Bluetooth/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp, lines 919–929. com_android_bluetooth_btservice_AdapterService.cpp fixed source.
android_bluetooth_UidTraffic.clazz =
(jclass)env->NewGlobalRef(env->FindClass("android/bluetooth/UidTraffic"));
sJniAdapterServiceObj = env->NewGlobalRef(obj);
sJniCallbacksObj = env->NewGlobalRef(env->GetObjectField(obj, sJniCallbacksField));
if (!sBluetoothInterface) {
return JNI_FALSE;
}
The JNI obj is actually AdapterNativeInterface; the historical variable name sJniAdapterServiceObj should not be taken as evidence of object type. After property callbacks are written to RemoteDevices, deviceFoundCallback then looks up the BluetoothDevice and DeviceProperties by address. DeviceProperties holds name, RSSI, device type, etc., and subsequently assembles the Intent; the App receives Parcelable device identity and extras, not Native property pointers.
13.4 Discovery Request Enters the Search State Machine via Binder
BluetoothAdapter.startDiscovery checks getState() == STATE_ON, calls callServiceIfEnabled(s -> s.startDiscovery(mAttributionSource), false) via AIDL; empty proxy and not enabled return false. AdapterServiceBinder's startDiscovery first uses getServiceAndEnforceCallerUserAndScan to check the available service, user, and scan permission, then goes to AdapterService.startDiscovery.
The service also checks the ownership between package name and Binder UID, state, location-related conditions, and puts the package name into mDiscoveringPackages. This is the basis for later distributing results by package; it is not a simple Native call. If ignoreRedundantDiscoveryIfSameState is effective and a discovery is already in progress, a redundant same-package call can return false; a new package can directly receive STARTED and share the existing discovery; sendDiscoveredDevToNewPkgs also controls re-issuing cached results. Even returning true may reuse an existing discovery; it does not guarantee a new Inquiry is generated. The lower-level main line here targets the first request when idle.
NativeInterface.startDiscovery enters startDiscoveryNative:
Source: packages/modules/Bluetooth/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp, lines 983–992. com_android_bluetooth_btservice_AdapterService.cpp fixed source.
static jboolean startDiscoveryNative(JNIEnv* /* env */, jobject /* obj */) {
log::verbose("");
if (!sBluetoothInterface) {
return JNI_FALSE;
}
int ret = sBluetoothInterface->start_discovery();
return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
}
BT_STATUS_SUCCESS is converted to Java true. Next, look at the Native implementation pointed to by the function table to know what "success" promises.
This function table also has a clear identity. The JNI registration function register_com_android_bluetooth_btservice_AdapterService saves the export table address:
Source: packages/modules/Bluetooth/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp, lines 1998–1998. com_android_bluetooth_btservice_AdapterService.cpp fixed source
sBluetoothInterface = &bluetoothInterface;
system/btif/src/bluetooth.cc defines the exported bt_interface_t bluetoothInterface, where the discovery and cancel fields bind to static implementations in the same file:
Source: packages/modules/Bluetooth/system/btif/src/bluetooth.cc, lines 1235–1236. bluetooth.cc fixed source
.start_discovery = start_discovery,
.cancel_discovery = cancel_discovery,
Therefore sBluetoothInterface->start_discovery() calls the start_discovery below, not a path guessed from a same-named function. The pointer selects the implementation in this process; the actual async scheduling happens later inside its do_in_main_thread.
Source: packages/modules/Bluetooth/system/btif/src/bluetooth.cc, lines 603–610. bluetooth.cc fixed source.
static int start_discovery(void) {
if (!interface_ready()) {
return BT_STATUS_NOT_READY;
}
do_in_main_thread(base::BindOnce(btif_dm_start_discovery));
return BT_STATUS_SUCCESS;
}
Here it first confirms the interface is ready, then posts btif_dm_start_discovery to the Native main thread. The JNI call is still on the thread it entered; the actual thread handoff occurs in do_in_main_thread. Native work and Binder return can interleave. The example calls the SDK on the App main thread and consumes broadcasts on the same main thread, so the REQUEST log for this call is written before the local receiver executes.
If the API were changed to synchronously wait for all discovery results and then return a list once, the caller would have to wait for the full scan and handle timeouts, cancellation, and discoveries shared by other apps. The current entry doesn't need to wait for discovery to complete; subsequent devices arrive one by one via broadcasts. The App can update the list early, but must manage its own observation window and accept that broadcasts have no request ID.
btif_dm_start_discovery first checks for an already queued search, initializes inquiry flags, then calls BTA_DmSearch(btif_dm_search_devices_evt). BTA_DmSearch delegates to bta_dm_disc_start_device_discovery, sending BTA_DM_API_SEARCH_EVT to the search state machine; the state machine's start action saves the callback and calls BTM_StartInquiry. If BTM returns non-BTM_CMD_STARTED, BTA goes through the completion path instead of pretending it started. BTM checks device up and inquiry-busy state, registers handlers for Inquiry results/completion, saves result and completion callbacks, then constructs the command.
Source: packages/modules/Bluetooth/system/stack/btm/btm_inq.cc, lines 727–738. btm_inq.cc fixed source.
// TODO: Register for the inquiry interface and use that
bluetooth::shim::GetHciLayer()->EnqueueCommand(
InquiryBuilder::Create(lap, btm_cb.btm_inq_vars.inqparms.duration, 0),
get_main_thread()->BindOnce([](CommandStatusView status_view) {
log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
auto status = status_view.GetStatus();
if (status == ErrorCode::SUCCESS) {
BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED);
} else {
log::info("Inquiry failed to start status: {}", ErrorCodeText(status));
}
}));
InquiryBuilder::Create carries LAP, duration unit, and response count limit; 0 means not ending early based on response count. HCI Inquiry's duration unit is 1.28 seconds; you cannot read the field directly as milliseconds. After Command Status succeeds, it reports inquiry started; it only indicates the controller accepted the command; subsequent result events and Inquiry Complete arrive independently. This function also calls BTM_StartLeScan. The selected Android implementation requests an LE scan when the controller supports BLE; the independent scanner's filtering and callbacks have a separate chain.
Look at the animated diagram showing how the App's return value and the controller's command status are written to two different objects.
13.5 HCI Commands Reach the Controller via HAL
What Passes Between HciLayer and HAL
HciLayer.EnqueueCommand's CommandStatusView overload enqueues via handler.CallOn; send_next_command, when there is command credit, no pending response command, and the queue is non-empty, serializes the builder into shared_ptr<vector<uint8_t>>, then calls hal_->sendHciCommand. The command queue stores the corresponding opcode and callback. Its credit management avoids stuffing an arbitrary number of commands directly at the controller; a HAL transport return is not the same as receiving Command Status.
Source: packages/modules/Bluetooth/system/gd/hci/hci_layer.cc, lines 365–372. hci_layer.cc fixed source.
return;
}
std::shared_ptr<std::vector<uint8_t>> bytes = std::make_shared<std::vector<uint8_t>>();
BitInserter bi(*bytes);
command_queue_.front().command->Serialize(bi);
hal_->sendHciCommand(*bytes);
auto cmd_view = CommandView::Create(PacketView<kLittleEndian>(bytes));
HciHalImpl.sendHciCommand first hands the bytes to the snoop logger, then calls the backend. HciHalImpl construction first tries HciBackend.CreateAidl(instance); only if AIDL is not declared does it fall back to HIDL. The AIDL branch uses the service name android.hardware.bluetooth.IBluetoothHci/default (when instance argument is empty), obtains a proxy via waitForService / fromBinder, creates AidlHciCallbacks for reverse callbacks, then initialize. AIDL/HIDL are a version-selected branch, not two layers drawn one after another. This article digs into the default AIDL implementation.
In this version of hardware/interfaces, the default service's service.cpp creates new BluetoothHci(), passes it through Bluetooth offload's hal/ffi.h into lib.rs::__add_bluetooth_hci_service to register a Binder service. AIDL sendHciCommand goes through the Rust HciProxy's module proxy chain, SinkModule, and FFI to call the implementation's BluetoothHci::sendHciCommand; you cannot attach another HciProxyAidl implementation under the new bluetooth_hal directory to the default service. The default implementation's Send prepends the H4 type byte to each packet, writes via writev to fd; events are read by AsyncFdWatcher, de-framed by H4, and handed to the hciEventReceived callback.
Cross-Language Bridge of the Default Service
This bridge has to track both "which implementation object" and "which HCI bytes". Look first at the service creation entry; the hci pointer comes from the freshly created default BluetoothHci:
Source: hardware/interfaces/bluetooth/aidl/default/service.cpp, lines 38–39. service.cpp fixed source.
IBluetoothHci_addService(new BluetoothHci());
ABinderProcess_joinThreadPool();
The C++ wrapper puts the instance pointer into CInterface.handle; lifetime still belongs to the HAL service; send_command is a callback function pointer whose instance is this handle:
Source: packages/modules/Bluetooth/offload/hal/include/hal/ffi.h, lines 119–121. ffi.h fixed source.
static inline void IBluetoothHci_addService(IBluetoothHci *hci) {
__add_bluetooth_hci_service((CInterface){
.handle = hci,
Source: packages/modules/Bluetooth/offload/hal/include/hal/ffi.h, lines 128–132. ffi.h fixed source.
.send_command =
[](void *instance, const uint8_t *data, size_t len) {
static_cast<IBluetoothHci *>(instance)->sendHciCommand(
std::vector<uint8_t>(data, data + len));
},
handle determines which implementation to call; data/len determine which bytes to hand over; they are not the same address. The Rust registration function puts the entire CInterface into Ffi, then wraps HciProxy as a Binder service:
Source: packages/modules/Bluetooth/offload/hal/lib.rs, lines 68–76. lib.rs fixed source.
binder::add_service(
&format!("{}/default", BpBluetoothHci::get_descriptor()),
BnBluetoothHci::new_binder(
HciProxy::new(vec![Box::new(LeAudioModuleBuilder {})], Ffi::new(cintf)),
binder::BinderFeatures::default(),
)
.as_binder(),
)
.expect("Failed to register service");
HciProxy.initialize constructs SinkModule and the module proxy chain, registers a death listener on callbacks, then marks Opened. AIDL sendHciCommand requires being Opened and calls proxy.out_cmd; for a normal Inquiry, LeAudioModule's default command branch passes through to the next module, not turning discovery into an audio operation.
Source: packages/modules/Bluetooth/offload/hal/service.rs, lines 114–121. service.rs fixed source.
fn sendHciCommand(&self, data: &[u8]) -> BinderResult<()> {
let State::Opened { ref proxy, .. } = *self.state.read().unwrap() else {
return Err(ExceptionCode::ILLEGAL_STATE.into());
};
proxy.out_cmd(data);
Ok(())
}
Source: packages/modules/Bluetooth/offload/hal/service.rs, lines 162–164. service.rs fixed source.
fn out_cmd(&self, data: &[u8]) {
self.ffi.send_command(data);
}
The terminal SinkModule hands the same bytes to Ffi; it holds the CInterface and calls back into C++ via the saved handle and function pointer under a Mutex:
Source: packages/modules/Bluetooth/offload/hal/ffi.rs, lines 106–114. ffi.rs fixed source.
fn send_command(&self, data: &[u8]) {
let intf = self.intf.lock().unwrap();
// SAFETY: The C Code has initialized the `CInterface` with a valid
// function pointer and an initialized `handle`.
unsafe {
(intf.send_command)(intf.handle, data.as_ptr(), data.len());
}
}
The call relationship is AIDL → HciProxy → module proxy chain → SinkModule → Ffi → CInterface.send_command(handle, data, len) → the original BluetoothHci instance. This is a function delegation and object-holding chain; it does not assume a new thread based on crossing a language boundary. The return-direction callback also goes back through the wrapper to AIDL; when observing H4 writev and the fd watcher, the calling object is already clear.
Branch One: Linux HCI User Channel and USB
The default initialize first creates NetBluetoothMgmt and attempts openHci. That function waits for an HCI device via the management channel, handles rfkill, then creates an AF_BLUETOOTH/SOCK_RAW/BTPROTO_HCI socket and binds HCI_CHANNEL_USER. This is not HCI_CHANNEL_RAW: the user channel has exclusive semantics for the device, and binding is subject to conditions such as CAP_NET_ADMIN and whether the device is busy.
Source: hardware/interfaces/bluetooth/aidl/default/net_bluetooth_mgmt.cpp, lines 267–281. net_bluetooth_mgmt.cpp fixed source.
// Open the raw HCI socket.
int fd = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
if (fd < 0) {
ALOGE("unable to open raw bluetooth socket: %s", strerror(errno));
return -1;
}
struct sockaddr_hci hci_addr = {
.hci_family = AF_BLUETOOTH,
.hci_dev = static_cast<uint16_t>(hci),
.hci_channel = HCI_CHANNEL_USER,
};
// Bind the socket to the selected interface.
if (bind(fd, (struct sockaddr*)&hci_addr, sizeof(hci_addr)) < 0) {
The kernel segment uses kernel/common commit ccafb60de224d35a8bc14de33e1cd47caaaa786b as an example, covering hci_sock.c, hci_core.c, btusb.c, and hci_ldisc.c. The running image and controller need their own evidence.
hci_sock_sendmsg interprets the first byte as the HCI packet type, strips the type byte, checks allowed packet types for the user channel, puts the packet into hdev->raw_q, and queue_work(tx_work). hci_tx_work takes raw_q and calls hci_send_frame; the latter calls the Driver callback registered in hdev->send. If the device is driven by btusb, its normal send branch hands Command packets to control URB and ACL to bulk URB; URB is a USB asynchronous transfer request, not a Bluetooth operation completion.
Source: this chapter's fixed kernel commit file btusb.c, lines 2146–2155.
switch (hci_skb_pkt_type(skb)) {
case HCI_COMMAND_PKT:
urb = alloc_ctrl_urb(hdev, skb);
if (IS_ERR(urb))
return PTR_ERR(urb);
hdev->stat.cmd_tx++;
return submit_or_queue_tx_urb(hdev, urb);
case HCI_ACLDATA_PKT:
The return direction is USB interrupt URB completion→btusb_recv_intr reassembling events→hci_recv_frame→rx_q/rx_work→hci_send_to_sock→user socket→HAL fd watcher. hci_rx_work, when HCI_USER_CHANNEL and not HCI_INIT, sends data to the socket, frees the skb, and skips normal Linux event/ACL protocol processing. Android consumes HCI events in userspace; Linux provides transport and device management on this path but does not take over Android's Profiles. USB firmware download, vendor setup, and special send callbacks may override the normal btusb branch; specific hardware must continue checking VID/PID, module, firmware, and binding.
UART may also provide a similar HCI device via the kernel's hci_uart: hdev->send registers as hci_uart_send_frame, protocol enqueue then wakes the transmitter, and TTY receive_buf hands to protocol parsing. This is a different arrangement from the HAL directly opening a character device below; you should not force the same packet into a "direct UART→Linux L2CAP→btusb" picture.
Branch Two: Direct Path and Virtual Controller
When openHci fails, the default HAL uses vendor.ser.bt-uart or the default /dev/hvc5, opens O_RDWR, sets a raw terminal, and uses H4Protocol for send/receive. The path being called hvc does not prove it is a physical UART; virtual serial ports can carry the same H4 data. Missing nodes, SELinux, service instance, and Host endpoint mismatches can all make initialization fail. In this version, the initialization code has subsequent statements after the error callback; do not infer a clean short-circuit shutdown from a single error log.
In the readable netsim branch, HciPacketTransport.Request hands packets to AsyncManager, schedules them synchronously, then calls the packet callback registered by RootCanal; the response goes back through Send→wireless.HandleResponse to the transport dispatcher. RootCanal's DualModeController.Inquiry parses the command parameters, calls BrEdrController.Inquiry and concurrently InquiryStatus; BrEdrController maintains inquiry state, periodically sends/receives simulated link-layer Inquiry, and results and timeouts become HCI events; cancellation clears inquiry state. It simulates the controller and does not replace the Android Host stack.
Source: tools/rootcanal/model/controller/bredr_controller.cc, lines 82–99. bredr_controller.cc fixed source.
ErrorCode BrEdrController::Inquiry(uint8_t lap, uint8_t inquiry_length, uint8_t num_responses) {
if (num_responses > 0xff || inquiry_length < 0x1 || inquiry_length > 0x30) {
return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
}
if (inquiry_.has_value()) {
INFO(id_, "Inquiry command is already pending");
return ErrorCode::COMMAND_DISALLOWED;
}
auto now = std::chrono::steady_clock::now();
inquiry_ = InquiryState{
.lap = lap,
.num_responses = num_responses,
.next_inquiry_event = now + kInquiryInterval,
.inquiry_timeout = now + std::chrono::milliseconds(inquiry_length * 1280),
};
Invalid length and an already-pending Inquiry can produce error states; without a simulated peer, the discovery may also complete normally with empty results. The tool source here is readable at a fixed commit; this machine's Emulator precompiled Host, startup parameters, guest fd, and this commit's netsim/RootCanal have not been one-to-one correlated. Therefore it is a clear candidate virtual backend, not claimed as the current instance's fact.
To actually identify the backend, you should simultaneously collect: running fingerprint / uname, VINTF and service process, the device or socket pointed to by the HAL fd, sysfs Driver/bus information, vendor.ser.bt-uart, Host command line, and netsim logs. Merely seeing a tools/netsim directory, Profile configuration, or the default value of /dev/hvc5 does not determine this round's path.
13.6 Device Properties Enter the Cache First, Discovery Results Are Then Broadcast
HCI's AIDL callback reaches AidlHciCallbacks.hciEventReceived; HciCallbacksImpl first records snoop and passes to HciLayer's hal_callbacks. It copies bytes to PacketView / EventView, posts on_hci_event via handler.CallOn. After that, dispatch by event code to the BTM callback previously registered and bound to the Native main handler. The thread that receives the HAL callback is separated from the thread that processes BTM state; the entire upstream path cannot be called the same Binder thread.
BTM's on_incoming_hci_event distinguishes Inquiry Complete, standard Inquiry Result, RSSI, and Extended variants. Results are parsed into tBTM_INQ_RESULTS, converted via the saved bta_dm_inq_results_cb to tBTA_DM_SEARCH.inq_res, then trigger the BTA_DM_INQ_RES_EVT in btif_dm_search_devices_evt. Address, RSSI, name/EIR, and device type are organized into a bt_property_t array. Array elements have type, len, val; val points to the address/local data at that moment, so a deep copy is needed before async handoff.
Source: packages/modules/Bluetooth/system/btif/src/bluetooth.cc, lines 1352–1361. bluetooth.cc fixed source.
void invoke_device_found_cb(int num_properties, bt_property_t* properties) {
do_in_jni_thread(base::BindOnce(
[](int num_properties, bt_property_t* properties) {
HAL_CBACK(bt_hal_cbacks, device_found_cb, num_properties, properties);
if (properties) {
osi_free(properties);
}
},
num_properties, property_deep_copy_array(num_properties, properties)));
}
property_deep_copy_array copies the properties before entering the JNI-thread task. After the task calls the callback, it uses osi_free to free the copy. If the async task only kept the original pointer, the local data pointed to by val could become invalid after the producer exits. Another approach is to give the task a well-defined shared-ownership object, which requires producer and consumer to agree on a lifetime contract. The current implementation hands the copy to the task, at the cost of allocation and copying on every handoff. The Native JNI's device_found_callback finds the address in the properties, converts it to a jbyteArray; first calls remote_device_properties_callback, then Java deviceFoundCallback. JNI local references are returned to the scope via ScopedLocalRef; async keep-alive relies on the earlier registered GlobalRef.
Source: packages/modules/Bluetooth/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp, lines 313–318. com_android_bluetooth_btservice_AdapterService.cpp fixed source.
// Add device properties before announcing device found
remote_device_properties_callback(BT_STATUS_SUCCESS, *addr, addr_type, num_properties,
properties);
sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_deviceFoundCallback, jaddr.get());
}
AdapterNativeCallback.kt hands property updates to RemoteDevices. RemoteDevices caches BluetoothDevice / DeviceProperties by address; deviceFoundCallback looks up the cache and calls AdapterService.discoveryResultHandler; the latter builds ACTION_FOUND from properties, puts EXTRA_DEVICE, EXTRA_RSSI, EXTRA_NAME, etc., iterates mDiscoveringPackages, and filters by permission and attribution to target packages. The App-registered BroadcastReceiver ultimately executes in the receiving dispatch environment it specifies; this example does not specify a Handler, so onReceive runs on the app main thread. It does not directly get the Native stack callback thread.
First see who receives the independent copy, then see which data still is retained by Java after the copy is freed.
The same state path sends BT_DISCOVERY_STARTED/STOPPED to AdapterProperties.discoveryStateChangeCallback. STOPPED sets mNativeDiscovering=false, clears discovery data, updates the end time, and sends ACTION_DISCOVERY_FINISHED. A natural completion may also include remote name handling; you cannot define Inquiry Complete and Java FINISHED as the same protocol event.
13.7 After Discovery, How Pairing, ACL, and Profiles Connect
After discovering a device, for normal pairing, call device.createBond(), default TRANSPORT_AUTO; it goes through IBluetooth.createBond→AdapterServiceBinder→AdapterService.createBond. The service checks already-bonded/bonding, dual-mode and feature flag branches, enabled, and package name, registers the initiator, cancels discovery, then sends MESSAGE_CREATE_BOND to BondStateMachine. msg.obj is the BluetoothDevice, arg1 is the transport.
BondStateMachine by default shares the Bluetooth process main Looper with AdapterService (default constructor passes Looper.getMainLooper). After consuming the message, it checks the current bond state, converts the device address to byte[], gets the address type, and calls NativeInterface.createBond. createBondNative converts to RawAddress; in this version, LE address type and transport affect whether create_bond_le or create_bond is called. The Native function first checks ready / pairing busy, then posts btif_dm_create_bond; subsequent BTA_DmBond and security manager branches negotiate keys. API true, Java enqueued, Native accepted, and authentication complete are different nodes. This is an interface explanation of the pairing main branch, not a packet-by-packet expansion of all SSP/SMP or CTKD.
Native bond_state_changed_callback returns to AdapterNativeCallback with status, address, transport, state, pairing algorithm/variant, and HCI reason. BondStateMachine.bondStateChangeCallback converts Native state to BOND_BONDING/BONDED/NONE and wraps it in MESSAGE_BOND_STATE_CHANGE. The state machine updates properties and sends ACTION_BOND_STATE_CHANGED; the App observes the final result via old/new state; PIN/SSP user confirmation is handled by the system UI. Failure must be explained with reason/status; you cannot call every return to BOND_NONE "cancel".
Profile proxies deal with obtaining the business interface. BluetoothAdapter.getProfileProxy creates the corresponding proxy according to PROFILE_CONSTRUCTORS, registers ProfileConnection, gets the Binder via getProfile; getProfileReply calls connection.connect, then notifies ServiceListener. Its true means the proxy-obtaining flow was accepted; onServiceConnected means the service interface is available, not that the remote device is connected. The A2DP connection-state broadcast describes the profile connection; actual media playback also requires audio routing and data channel evidence. This chapter doesn't hand audio data to the Inquiry command chain, nor wait for the Audio chapter's output.
After obtaining the Profile proxy, query connection state per the interface; when done pairing, call closeProfileProxy; closing the proxy is a local service interface cleanup, not equivalent to disconnecting the device's audio connection. Traditional A2DP data goes through the Native audio/protocol path with HCI ACL or offload branches; LE Audio may involve ISO; the specific transport and audio HAL are confirmed further in the Audio scenario.
13.8 Cancel Requests, System Stop, and Local Exit
When locally stopping observation, the example tries to use cancelDiscovery() to request cancellation of an accepted discovery. The synchronous return and the system end broadcast are two observation points. If ignoreRedundantDiscoveryIfSameState is effective, AdapterService removes the calling package from mDiscoveringPackages; with other packages present it can return true without issuing a global cancel. On the old branch or last package it continues with Native cancel_discovery→main thread btif_dm_cancel_discovery→BTA_DmSearchCancel→search state machine→BTM cancel/name cancel and final completion.
BTM_CancelInquiry, when active, sends InquiryCancel, processes its Command Complete, and stops related LE scanning; discovery end also requires handling search state, pending requests, and name queries; it does not require the controller to emit a natural Inquiry Complete after cancel. RootCanal's InquiryCancel only succeeds when there is an active inquiry, clears state, and returns the completion response; animations and criteria cannot force both completions to appear simultaneously.
There are two paths here that cannot be drawn as a fixed order. The active-Inquiry branch, after draining the cancel command, directly continues notifications and finishes search state:
Source: packages/modules/Bluetooth/system/bta/dm/bta_dm_device_search.cc, lines 130–135. bta_dm_device_search.cc fixed source
static void bta_dm_search_cancel() {
if (BTM_IsInquiryActive()) {
BTM_CancelInquiry();
bta_dm_search_cancel_notify();
bta_dm_search_cmpl();
} else if (!bta_dm_search_cb.name_discover_done) {
BTM_CancelInquiry does not wait for HCI Command Complete; bta_dm_search_cmpl can first report STOPPED via BTA_DM_DISC_CMPL_EVT. The HCI cancel response may later report STOPPED via btm_process_cancel_complete; fix_multiple_discovery_stopped_broadcast controls duplicate state filtering. Java FINISHED, App LOCAL_END, and controller cancel response are not the same endpoint; you cannot infer a global order guarantee from illustrative layout.
In the figure, compare these two outcomes: the App's own receiver shut down vs. the system discovery continuing.
When FINISHED broadcast is received, the example cleans up the Receiver and timer task. On user stop, leaving foreground, or about 25 seconds without observing an end, an accepted round still attempts cancel. A request returning false or throwing only cleans up locally, avoiding turning a rejected request into a cancellation of an existing discovery. Whether the system side has registered, and when the search stops, needs to be judged with service state and HCI logs.
| Phenomenon | Where to check first | What cannot be directly inferred |
|---|---|---|
| startDiscovery false / SecurityException | Bluetooth state, SCAN/CONNECT, user/package attribution, duplicate requests | Controller broken |
| true then no STARTED | log observer, queuing, reuse branch, Native/HCI state | No HCI was definitely sent |
| FINISHED and no FOUND | peer discoverable mode, BR/EDR capability, distance/virtual peer, filter conditions | This round's discovery implementation failed |
| snoop has results, App has none | property parsing, permission filtering, package registration, receiver window | Wireless controller didn't receive anything |
| cancel true but system still discovering | other scanning packages, flags, in-flight events and name queries | Cancel is globally complete |
| HAL initialization failure or death | VINTF/instance, fd/SELinux, user channel busy, Host endpoint | Restarting the App alone will recover |
| bond back to NONE | status, reason, user confirmation and peer state | It's just user cancel |
On normal service end, Native cleans the stack, JNI GlobalRefs, and callback associations; HciHalImpl destructor resets the backend; AidlHci destructor removes the death recipient and calls HAL.close. The default HAL.close stops the fd watcher, closes the user channel or direct fd, clears H4, and returns to READY; clientDied also goes through close. An app process exit makes the dynamic receiver end with the process, but that does not replace the explicit cleanup in the example's normal onStop, nor does it prove the controller stops instantly. HAL death has a fatal recovery strategy in this version's AIDL client; it should not be described as a transparent, lossless reconnection.
13.9 Trace Discovery Progress by Logs
First confirm REQUEST in Logcat, then look at STARTED, FOUND, FINISHED, and LOCAL_END. To go deeper into the system, start from AdapterService's package registration, follow Native scheduling, HCI commands, and the chosen transport of HAL to the controller, then come back from event parsing, property copying, and Java cache to the app broadcast.
Look up symbols by question: entry and proxy to BluetoothManager / BluetoothAdapter; attribution and distribution to AdapterServiceBinder / AdapterService; async acceptance to bluetooth.cc::start_discovery; search state to bta_dm_device_search.cc; Inquiry packing and events to btm_inq.cc; HCI queue to hci_layer.cc; transport selection to hci_hal_impl_android.cc / hci_backend_aidl.cc / default BluetoothHci.cpp; callback and release to invoke_device_found_cb / AdapterNativeCallback.kt / RemoteDevices.
- Can startDiscovery true prove devices have been found? Answer: No; the return in 13.4 does not wait for async task completion, cannot prove the controller accepted or discovered devices, and may share an existing discovery.
- Does the HCI user channel make Android use Linux L2CAP? Answer: No; the user channel receive branch in 13.5 skips normal Linux protocol processing; the Android stack still consumes events.
- Why do properties need a deep copy? Answer: bt_property_t.val may point to current function local data; the async task in 13.6 must extend its data lifetime.
- Is FINISHED with zero devices a failure? Answer: Not necessarily; first validate prerequisites with a controlled peer and backend capabilities, see 13.2, 13.8.
- Does getProfileProxy's onServiceConnected mean the headset is connected? Answer: Only the service interface is available; profile connection and audio output require independent evidence, see 13.7.
- After timeout, cancel true, can we judge the controller has stopped? Answer: Also compare the same round's HCI cancel response and backend logs, see Appendix B.
Appendix A|Runnable Discovery Example
After creating the project as in 13.2, overwrite the following two files. The template's namespace and applicationId use com.example.btstudy. The UI is created by the Activity; no extra dependencies or layout resources are needed.
app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth" android:required="true" />
<application android:label="Bluetooth Round Discovery" android:theme="@android:style/Theme.Material.Light.NoActionBar">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
app/src/main/java/com/example/btstudy/MainActivity.java
package com.example.btstudy;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Insets;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.WindowInsets;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ScrollView;
public final class MainActivity extends Activity {
private final Handler handler = new Handler(Looper.getMainLooper());
private BluetoothAdapter adapter;
private TextView status;
private boolean active, registered, discoveryAccepted;
private int round;
private Runnable timeout;
private void event(String text) {
String line = "round=" + round + " elapsedMs=" + SystemClock.elapsedRealtime()
+ " " + text;
Log.i("BtStudy", line);
status.append(line + "\n");
}
private boolean permissionsReady() {
return checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN)
== PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)
== PackageManager.PERMISSION_GRANTED;
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
if (!active) return;
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
event("STARTED");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE, BluetoothDevice.class);
if (device != null) {
String rssi = intent.hasExtra(BluetoothDevice.EXTRA_RSSI)
? Short.toString(intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, (short) 0))
: "unknown";
String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
event("FOUND address=" + device.getAddress()
+ " name=" + name + " rssiDbm=" + rssi);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
event("FINISHED");
end("finished-broadcast", false);
}
}
};
@Override public void onCreate(Bundle state) {
super.onCreate(state);
BluetoothManager manager = getSystemService(BluetoothManager.class);
adapter = manager == null ? null : manager.getAdapter();
LinearLayout box = new LinearLayout(this);
box.setOrientation(LinearLayout.VERTICAL);
int padding = Math.round(12 * getResources().getDisplayMetrics().density);
box.setOnApplyWindowInsetsListener((view, insets) -> {
Insets bars = insets.getInsets(WindowInsets.Type.systemBars());
view.setPadding(bars.left + padding, bars.top + padding,
bars.right + padding, bars.bottom + padding);
return insets;
});
status = new TextView(this);
Button start = new Button(this);
start.setText("Start a round of discovery / Request permission");
start.setOnClickListener(v -> begin());
Button stop = new Button(this);
stop.setText("End local observation and request cancel");
stop.setOnClickListener(v -> end("user-stop", true));
box.addView(start);
box.addView(stop);
ScrollView logView = new ScrollView(this);
logView.addView(status);
box.addView(logView, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 0, 1));
setContentView(box);
event("READY. Enable Bluetooth in settings, then click start");
}
private void begin() {
if (active) { event("ALREADY_ACTIVE"); return; }
if (!permissionsReady()) {
requestPermissions(new String[] {Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT}, 1);
event("After authorization, click start again; if denied, no request is sent");
return;
}
if (adapter == null) {
event("NO_ADAPTER. This image does not provide a Bluetooth Adapter");
return;
}
if (!adapter.isEnabled()) {
event("BLUETOOTH_OFF. Enable Bluetooth in settings");
return;
}
round++;
status.setText("");
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
try {
registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED);
registered = true;
active = true;
discoveryAccepted = adapter.startDiscovery();
event("REQUEST accepted=" + discoveryAccepted);
if (!discoveryAccepted) {
end("request-rejected", false);
return;
}
final int expectedRound = round;
timeout = () -> {
if (active && round == expectedRound) end("timeout-25s", true);
};
handler.postDelayed(timeout, 25_000);
} catch (SecurityException e) {
event("REQUEST SecurityException");
end("permission-error", false);
}
}
private void end(String reason, boolean cancel) {
if (!active && !registered) return;
active = false;
if (timeout != null) handler.removeCallbacks(timeout);
timeout = null;
if (cancel && discoveryAccepted && permissionsReady()) {
try { event("CANCEL accepted=" + adapter.cancelDiscovery()); }
catch (SecurityException e) { event("CANCEL SecurityException"); }
}
discoveryAccepted = false;
if (registered) { unregisterReceiver(receiver); registered = false; }
event("LOCAL_END reason=" + reason);
}
@Override protected void onStop() {
end("onStop", true);
super.onStop();
}
}
Appendix B|Compare App Logs with HCI
The App from 13.2 can be installed on a controlled device by Android Studio as usual. Turn on Developer Options' Bluetooth HCI snoop log and restart Bluetooth as required by the test device. In terminal A, set the actual serial number and save the runtime baseline. The other terminal must set the same serial number independently.
export SERIAL=your-test-serial
RUN_DIR=$(mktemp -d) && (
set -e
adb -s "$SERIAL" shell getprop ro.build.fingerprint > "$RUN_DIR/fingerprint.txt"
adb -s "$SERIAL" shell dumpsys bluetooth_manager > "$RUN_DIR/bluetooth-before.txt"
printf '%s\n' "$RUN_DIR"
)
In terminal B, start Logcat collection. Replace the path with the directory actually printed in terminal A, and confirm both ends use the same device number. Keep the observer running, initiate a round in the App, and wait for end or stop actively.
export SERIAL=your-test-serial
RUN_DIR='/replace/with/printed/path'
(
set -o pipefail
test -d "$RUN_DIR" || exit 1
adb -s "$SERIAL" logcat -v threadtime BtStudy:I '*:S' 2>&1 | tee "$RUN_DIR/app.log"
)
After the round ends, collect system state and bugreport in terminal A.
test -d "$RUN_DIR" && (
set -e
adb -s "$SERIAL" shell dumpsys bluetooth_manager > "$RUN_DIR/bluetooth-after.txt"
adb -s "$SERIAL" bugreport "$RUN_DIR/bluetooth-bugreport.zip"
test -s "$RUN_DIR/bluetooth-bugreport.zip"
)
Find the btsnoop file for this round in the archive, then in Wireshark look up Inquiry (opcode 0x0401), Command Status, the Inquiry Result family, and Inquiry Complete. For the cancel path, also look up Inquiry Cancel (0x0402) and Command Complete. If no snoop for this round is in the archive, keep the App-side conclusions and continue locating via the product-supported collection entry.
elapsedMs is monotonically clock since boot and includes sleep. Logcat's default date-time is a different clock. First mark the App observation window with the same round's REQUEST and LOCAL_END, then combine event addresses, operation times, and states to check HCI. Inquiry may predate REQUEST, and the cancel response may come after LOCAL_END, so collection should start before the tap and continue until the system end is observed or another collection time limit is reached. Stop terminal B's collection, restore HCI snoop settings, and restart Bluetooth as required by the product. These are follow-along steps; there is no corresponding device run record at this time.
Source Versions
| Project | Fixed commit | Scope |
|---|---|---|
| packages/modules/Bluetooth | c77db469de80f86660bc053bec4dee0c5d4b947c |
SDK, Adapter service, BTIF/BTA/BTM, HCI, HAL FFI |
| hardware/interfaces | 0162af698935100a590b7359581ac8b1b80693e5 |
Bluetooth default AIDL HAL |
| tools/rootcanal | 559446380c3e2cf01c82608897ba5a246996fe5c |
Virtual controller and Inquiry |
| tools/netsim | 71feaeea338b3bd7eda6914cc9b9b382d752957d |
Virtual HCI packet transport |
| device/generic/goldfish | 296e55aa0244e8929e393e00e34471fef2a5d662 |
Emulator product config clues |
| kernel/common | ccafb60de224d35a8bc14de33e1cd47caaaa786b |
HCI socket, USB and TTY drivers |
Top 1 from juejin.cn, machine-translated. The original thread is authoritative.
Let me add a time constant that matches your section 13.1: the official comment for startDiscovery says the inquiry scan lasts about 12 seconds, and only then does it do a page scan for each newly discovered device to fetch the name. So FOUND arriving first and the name arriving later are two separate actions, not a single callback. If the name stays empty, it's usually not that the device is broken; it's that that particular page scan didn't succeed. Identify the device by address and RSSI for now. The same comment also has a line that's rarely mentioned: discovery is a heavyweight operation; don't create new connections during discovery, and existing connections will lose bandwidth and gain latency. It explicitly requires that even if this round of discovery wasn't initiated by you, you should still call cancelDiscovery, because discovery runs as a system service and isn't under your Activity's control. Another counterexample: the list stays empty. The comment states that only devices that are in a discoverable state and have inquiry scan enabled will be found. Many devices are not visible by default; you have to long-press to enter pairing mode. For such an empty list, the fault isn't in the code. I didn't follow the branch about package-name-based sharing determination in section 13.8; the above points are only based on the comments and real-device behavior.