fun disable(adapter: BluetoothAdapter) { var mask: Int = BluetoothReceiver.STATE_TURNING_OFF_FLAG or BluetoothReceiver.STATE_OFF_FLAG or BluetoothReceiver.SCAN_MODE_NONE_FLAG var start: Long = -1 val receiver: BluetoothReceiver = getBluetoothReceiver(mask) var state = adapter.state when (state) { BluetoothAdapter.STATE_OFF -> { assertFalse(adapter.isEnabled) removeReceiver(receiver) return } BluetoothAdapter.STATE_TURNING_ON -> { assertFalse(adapter.isEnabled) start = System.currentTimeMillis() } BluetoothAdapter.STATE_ON -> { assertTrue(adapter.isEnabled) start = System.currentTimeMillis() assertTrue(adapter.disable()) } BluetoothAdapter.STATE_TURNING_OFF -> { assertFalse(adapter.isEnabled) mask = 0 } else -> { removeReceiver(receiver) fail(String.format("disable() invalid state: state=%d", state)) } } val s = System.currentTimeMillis() while (System.currentTimeMillis() - s < ENABLE_DISABLE_TIMEOUT) { state = adapter.state if (state == BluetoothAdapter.STATE_OFF && receiver.getFiredFlags() and mask === mask) { assertFalse(adapter.isEnabled) val finish: Long = receiver.getCompletedTime() if (start != -1L && finish != -1L) { writeOutput(String.format("disable() completed in %d ms", finish - start)) } else { writeOutput("disable() completed") } removeReceiver(receiver) return } sleep(POLL_TIME) } val firedFlags: Int = receiver.getFiredFlags() removeReceiver(receiver) fail( String.format( "disable() timeout: state=%d (expected %d), flags=0x%x (expected 0x%x)", state, BluetoothAdapter.STATE_OFF, firedFlags, mask ) ) }
Disables Bluetooth and checks to make sure that Bluetooth was turned off and that the correct actions were broadcast .