BluetoothAdapter.java revision 876d100f0234dd111d84abdec8187e6834ee7573
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.bluetooth; 18 19import android.annotation.SdkConstant; 20import android.annotation.SdkConstant.SdkConstantType; 21import android.content.Context; 22import android.os.Binder; 23import android.os.IBinder; 24import android.os.Message; 25import android.os.ParcelUuid; 26import android.os.RemoteException; 27import android.os.ServiceManager; 28import android.util.Log; 29import android.util.Pair; 30 31import java.io.IOException; 32import java.lang.ref.WeakReference; 33import java.util.ArrayList; 34import java.util.Arrays; 35import java.util.Collections; 36import java.util.HashSet; 37import java.util.HashMap; 38import java.util.LinkedList; 39import java.util.Locale; 40import java.util.Map; 41import java.util.Random; 42import java.util.Set; 43import java.util.UUID; 44 45/** 46 * Represents the local device Bluetooth adapter. The {@link BluetoothAdapter} 47 * lets you perform fundamental Bluetooth tasks, such as initiate 48 * device discovery, query a list of bonded (paired) devices, 49 * instantiate a {@link BluetoothDevice} using a known MAC address, and create 50 * a {@link BluetoothServerSocket} to listen for connection requests from other 51 * devices, and start a scan for Bluetooth LE devices. 52 * 53 * <p>To get a {@link BluetoothAdapter} representing the local Bluetooth 54 * adapter, when running on JELLY_BEAN_MR1 and below, call the 55 * static {@link #getDefaultAdapter} method; when running on JELLY_BEAN_MR2 and 56 * higher, retrieve it through 57 * {@link android.content.Context#getSystemService} with 58 * {@link android.content.Context#BLUETOOTH_SERVICE}. 59 * Fundamentally, this is your starting point for all 60 * Bluetooth actions. Once you have the local adapter, you can get a set of 61 * {@link BluetoothDevice} objects representing all paired devices with 62 * {@link #getBondedDevices()}; start device discovery with 63 * {@link #startDiscovery()}; or create a {@link BluetoothServerSocket} to 64 * listen for incoming connection requests with 65 * {@link #listenUsingRfcommWithServiceRecord(String,UUID)}; or start a scan for 66 * Bluetooth LE devices with {@link #startLeScan(LeScanCallback callback)}. 67 * 68 * <p class="note"><strong>Note:</strong> 69 * Most methods require the {@link android.Manifest.permission#BLUETOOTH} 70 * permission and some also require the 71 * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission. 72 * 73 * <div class="special reference"> 74 * <h3>Developer Guides</h3> 75 * <p>For more information about using Bluetooth, read the 76 * <a href="{@docRoot}guide/topics/wireless/bluetooth.html">Bluetooth</a> developer guide.</p> 77 * </div> 78 * 79 * {@see BluetoothDevice} 80 * {@see BluetoothServerSocket} 81 */ 82public final class BluetoothAdapter { 83 private static final String TAG = "BluetoothAdapter"; 84 private static final boolean DBG = true; 85 private static final boolean VDBG = false; 86 87 /** 88 * Sentinel error value for this class. Guaranteed to not equal any other 89 * integer constant in this class. Provided as a convenience for functions 90 * that require a sentinel error value, for example: 91 * <p><code>Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 92 * BluetoothAdapter.ERROR)</code> 93 */ 94 public static final int ERROR = Integer.MIN_VALUE; 95 96 /** 97 * Broadcast Action: The state of the local Bluetooth adapter has been 98 * changed. 99 * <p>For example, Bluetooth has been turned on or off. 100 * <p>Always contains the extra fields {@link #EXTRA_STATE} and {@link 101 * #EXTRA_PREVIOUS_STATE} containing the new and old states 102 * respectively. 103 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 104 */ 105 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 106 public static final String ACTION_STATE_CHANGED = 107 "android.bluetooth.adapter.action.STATE_CHANGED"; 108 109 /** 110 * Used as an int extra field in {@link #ACTION_STATE_CHANGED} 111 * intents to request the current power state. Possible values are: 112 * {@link #STATE_OFF}, 113 * {@link #STATE_TURNING_ON}, 114 * {@link #STATE_ON}, 115 * {@link #STATE_TURNING_OFF}, 116 */ 117 public static final String EXTRA_STATE = 118 "android.bluetooth.adapter.extra.STATE"; 119 /** 120 * Used as an int extra field in {@link #ACTION_STATE_CHANGED} 121 * intents to request the previous power state. Possible values are: 122 * {@link #STATE_OFF}, 123 * {@link #STATE_TURNING_ON}, 124 * {@link #STATE_ON}, 125 * {@link #STATE_TURNING_OFF}, 126 */ 127 public static final String EXTRA_PREVIOUS_STATE = 128 "android.bluetooth.adapter.extra.PREVIOUS_STATE"; 129 130 /** 131 * Indicates the local Bluetooth adapter is off. 132 */ 133 public static final int STATE_OFF = 10; 134 /** 135 * Indicates the local Bluetooth adapter is turning on. However local 136 * clients should wait for {@link #STATE_ON} before attempting to 137 * use the adapter. 138 */ 139 public static final int STATE_TURNING_ON = 11; 140 /** 141 * Indicates the local Bluetooth adapter is on, and ready for use. 142 */ 143 public static final int STATE_ON = 12; 144 /** 145 * Indicates the local Bluetooth adapter is turning off. Local clients 146 * should immediately attempt graceful disconnection of any remote links. 147 */ 148 public static final int STATE_TURNING_OFF = 13; 149 150 /** 151 * Activity Action: Show a system activity that requests discoverable mode. 152 * This activity will also request the user to turn on Bluetooth if it 153 * is not currently enabled. 154 * <p>Discoverable mode is equivalent to {@link 155 * #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. It allows remote devices to see 156 * this Bluetooth adapter when they perform a discovery. 157 * <p>For privacy, Android is not discoverable by default. 158 * <p>The sender of this Intent can optionally use extra field {@link 159 * #EXTRA_DISCOVERABLE_DURATION} to request the duration of 160 * discoverability. Currently the default duration is 120 seconds, and 161 * maximum duration is capped at 300 seconds for each request. 162 * <p>Notification of the result of this activity is posted using the 163 * {@link android.app.Activity#onActivityResult} callback. The 164 * <code>resultCode</code> 165 * will be the duration (in seconds) of discoverability or 166 * {@link android.app.Activity#RESULT_CANCELED} if the user rejected 167 * discoverability or an error has occurred. 168 * <p>Applications can also listen for {@link #ACTION_SCAN_MODE_CHANGED} 169 * for global notification whenever the scan mode changes. For example, an 170 * application can be notified when the device has ended discoverability. 171 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 172 */ 173 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 174 public static final String ACTION_REQUEST_DISCOVERABLE = 175 "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE"; 176 177 /** 178 * Used as an optional int extra field in {@link 179 * #ACTION_REQUEST_DISCOVERABLE} intents to request a specific duration 180 * for discoverability in seconds. The current default is 120 seconds, and 181 * requests over 300 seconds will be capped. These values could change. 182 */ 183 public static final String EXTRA_DISCOVERABLE_DURATION = 184 "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION"; 185 186 /** 187 * Activity Action: Show a system activity that allows the user to turn on 188 * Bluetooth. 189 * <p>This system activity will return once Bluetooth has completed turning 190 * on, or the user has decided not to turn Bluetooth on. 191 * <p>Notification of the result of this activity is posted using the 192 * {@link android.app.Activity#onActivityResult} callback. The 193 * <code>resultCode</code> 194 * will be {@link android.app.Activity#RESULT_OK} if Bluetooth has been 195 * turned on or {@link android.app.Activity#RESULT_CANCELED} if the user 196 * has rejected the request or an error has occurred. 197 * <p>Applications can also listen for {@link #ACTION_STATE_CHANGED} 198 * for global notification whenever Bluetooth is turned on or off. 199 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 200 */ 201 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 202 public static final String ACTION_REQUEST_ENABLE = 203 "android.bluetooth.adapter.action.REQUEST_ENABLE"; 204 205 /** 206 * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter 207 * has changed. 208 * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link 209 * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes 210 * respectively. 211 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 212 */ 213 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 214 public static final String ACTION_SCAN_MODE_CHANGED = 215 "android.bluetooth.adapter.action.SCAN_MODE_CHANGED"; 216 217 /** 218 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED} 219 * intents to request the current scan mode. Possible values are: 220 * {@link #SCAN_MODE_NONE}, 221 * {@link #SCAN_MODE_CONNECTABLE}, 222 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}, 223 */ 224 public static final String EXTRA_SCAN_MODE = "android.bluetooth.adapter.extra.SCAN_MODE"; 225 /** 226 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED} 227 * intents to request the previous scan mode. Possible values are: 228 * {@link #SCAN_MODE_NONE}, 229 * {@link #SCAN_MODE_CONNECTABLE}, 230 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}, 231 */ 232 public static final String EXTRA_PREVIOUS_SCAN_MODE = 233 "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE"; 234 235 /** 236 * Indicates that both inquiry scan and page scan are disabled on the local 237 * Bluetooth adapter. Therefore this device is neither discoverable 238 * nor connectable from remote Bluetooth devices. 239 */ 240 public static final int SCAN_MODE_NONE = 20; 241 /** 242 * Indicates that inquiry scan is disabled, but page scan is enabled on the 243 * local Bluetooth adapter. Therefore this device is not discoverable from 244 * remote Bluetooth devices, but is connectable from remote devices that 245 * have previously discovered this device. 246 */ 247 public static final int SCAN_MODE_CONNECTABLE = 21; 248 /** 249 * Indicates that both inquiry scan and page scan are enabled on the local 250 * Bluetooth adapter. Therefore this device is both discoverable and 251 * connectable from remote Bluetooth devices. 252 */ 253 public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23; 254 255 256 /** 257 * Broadcast Action: The local Bluetooth adapter has started the remote 258 * device discovery process. 259 * <p>This usually involves an inquiry scan of about 12 seconds, followed 260 * by a page scan of each new device to retrieve its Bluetooth name. 261 * <p>Register for {@link BluetoothDevice#ACTION_FOUND} to be notified as 262 * remote Bluetooth devices are found. 263 * <p>Device discovery is a heavyweight procedure. New connections to 264 * remote Bluetooth devices should not be attempted while discovery is in 265 * progress, and existing connections will experience limited bandwidth 266 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 267 * discovery. 268 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 269 */ 270 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 271 public static final String ACTION_DISCOVERY_STARTED = 272 "android.bluetooth.adapter.action.DISCOVERY_STARTED"; 273 /** 274 * Broadcast Action: The local Bluetooth adapter has finished the device 275 * discovery process. 276 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 277 */ 278 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 279 public static final String ACTION_DISCOVERY_FINISHED = 280 "android.bluetooth.adapter.action.DISCOVERY_FINISHED"; 281 282 /** 283 * Broadcast Action: The local Bluetooth adapter has changed its friendly 284 * Bluetooth name. 285 * <p>This name is visible to remote Bluetooth devices. 286 * <p>Always contains the extra field {@link #EXTRA_LOCAL_NAME} containing 287 * the name. 288 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 289 */ 290 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 291 public static final String ACTION_LOCAL_NAME_CHANGED = 292 "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED"; 293 /** 294 * Used as a String extra field in {@link #ACTION_LOCAL_NAME_CHANGED} 295 * intents to request the local Bluetooth name. 296 */ 297 public static final String EXTRA_LOCAL_NAME = "android.bluetooth.adapter.extra.LOCAL_NAME"; 298 299 /** 300 * Intent used to broadcast the change in connection state of the local 301 * Bluetooth adapter to a profile of the remote device. When the adapter is 302 * not connected to any profiles of any remote devices and it attempts a 303 * connection to a profile this intent will sent. Once connected, this intent 304 * will not be sent for any more connection attempts to any profiles of any 305 * remote device. When the adapter disconnects from the last profile its 306 * connected to of any remote device, this intent will be sent. 307 * 308 * <p> This intent is useful for applications that are only concerned about 309 * whether the local adapter is connected to any profile of any device and 310 * are not really concerned about which profile. For example, an application 311 * which displays an icon to display whether Bluetooth is connected or not 312 * can use this intent. 313 * 314 * <p>This intent will have 3 extras: 315 * {@link #EXTRA_CONNECTION_STATE} - The current connection state. 316 * {@link #EXTRA_PREVIOUS_CONNECTION_STATE}- The previous connection state. 317 * {@link BluetoothDevice#EXTRA_DEVICE} - The remote device. 318 * 319 * {@link #EXTRA_CONNECTION_STATE} or {@link #EXTRA_PREVIOUS_CONNECTION_STATE} 320 * can be any of {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING}, 321 * {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}. 322 * 323 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 324 */ 325 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 326 public static final String ACTION_CONNECTION_STATE_CHANGED = 327 "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED"; 328 329 /** 330 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED} 331 * 332 * This extra represents the current connection state. 333 */ 334 public static final String EXTRA_CONNECTION_STATE = 335 "android.bluetooth.adapter.extra.CONNECTION_STATE"; 336 337 /** 338 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED} 339 * 340 * This extra represents the previous connection state. 341 */ 342 public static final String EXTRA_PREVIOUS_CONNECTION_STATE = 343 "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE"; 344 345 /** The profile is in disconnected state */ 346 public static final int STATE_DISCONNECTED = 0; 347 /** The profile is in connecting state */ 348 public static final int STATE_CONNECTING = 1; 349 /** The profile is in connected state */ 350 public static final int STATE_CONNECTED = 2; 351 /** The profile is in disconnecting state */ 352 public static final int STATE_DISCONNECTING = 3; 353 354 /** @hide */ 355 public static final String BLUETOOTH_MANAGER_SERVICE = "bluetooth_manager"; 356 357 private static final int ADDRESS_LENGTH = 17; 358 359 /** 360 * Lazily initialized singleton. Guaranteed final after first object 361 * constructed. 362 */ 363 private static BluetoothAdapter sAdapter; 364 365 private final IBluetoothManager mManagerService; 366 private IBluetooth mService; 367 368 private final Map<LeScanCallback, GattCallbackWrapper> mLeScanClients; 369 370 /** 371 * Get a handle to the default local Bluetooth adapter. 372 * <p>Currently Android only supports one Bluetooth adapter, but the API 373 * could be extended to support more. This will always return the default 374 * adapter. 375 * @return the default local adapter, or null if Bluetooth is not supported 376 * on this hardware platform 377 */ 378 public static synchronized BluetoothAdapter getDefaultAdapter() { 379 if (sAdapter == null) { 380 IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE); 381 if (b != null) { 382 IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b); 383 sAdapter = new BluetoothAdapter(managerService); 384 } else { 385 Log.e(TAG, "Bluetooth binder is null"); 386 } 387 } 388 return sAdapter; 389 } 390 391 /** 392 * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance. 393 */ 394 BluetoothAdapter(IBluetoothManager managerService) { 395 396 if (managerService == null) { 397 throw new IllegalArgumentException("bluetooth manager service is null"); 398 } 399 try { 400 mService = managerService.registerAdapter(mManagerCallback); 401 } catch (RemoteException e) {Log.e(TAG, "", e);} 402 mManagerService = managerService; 403 mLeScanClients = new HashMap<LeScanCallback, GattCallbackWrapper>(); 404 } 405 406 /** 407 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware 408 * address. 409 * <p>Valid Bluetooth hardware addresses must be upper case, in a format 410 * such as "00:11:22:33:AA:BB". The helper {@link #checkBluetoothAddress} is 411 * available to validate a Bluetooth address. 412 * <p>A {@link BluetoothDevice} will always be returned for a valid 413 * hardware address, even if this adapter has never seen that device. 414 * 415 * @param address valid Bluetooth MAC address 416 * @throws IllegalArgumentException if address is invalid 417 */ 418 public BluetoothDevice getRemoteDevice(String address) { 419 return new BluetoothDevice(address); 420 } 421 422 /** 423 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware 424 * address. 425 * <p>Valid Bluetooth hardware addresses must be 6 bytes. This method 426 * expects the address in network byte order (MSB first). 427 * <p>A {@link BluetoothDevice} will always be returned for a valid 428 * hardware address, even if this adapter has never seen that device. 429 * 430 * @param address Bluetooth MAC address (6 bytes) 431 * @throws IllegalArgumentException if address is invalid 432 */ 433 public BluetoothDevice getRemoteDevice(byte[] address) { 434 if (address == null || address.length != 6) { 435 throw new IllegalArgumentException("Bluetooth address must have 6 bytes"); 436 } 437 return new BluetoothDevice(String.format(Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X", 438 address[0], address[1], address[2], address[3], address[4], address[5])); 439 } 440 441 /** 442 * Return true if Bluetooth is currently enabled and ready for use. 443 * <p>Equivalent to: 444 * <code>getBluetoothState() == STATE_ON</code> 445 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 446 * 447 * @return true if the local adapter is turned on 448 */ 449 public boolean isEnabled() { 450 451 try { 452 synchronized(mManagerCallback) { 453 if (mService != null) return mService.isEnabled(); 454 } 455 } catch (RemoteException e) {Log.e(TAG, "", e);} 456 return false; 457 } 458 459 /** 460 * Get the current state of the local Bluetooth adapter. 461 * <p>Possible return values are 462 * {@link #STATE_OFF}, 463 * {@link #STATE_TURNING_ON}, 464 * {@link #STATE_ON}, 465 * {@link #STATE_TURNING_OFF}. 466 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 467 * 468 * @return current state of Bluetooth adapter 469 */ 470 public int getState() { 471 try { 472 synchronized(mManagerCallback) { 473 if (mService != null) 474 { 475 int state= mService.getState(); 476 if (VDBG) Log.d(TAG, "" + hashCode() + ": getState(). Returning " + state); 477 return state; 478 } 479 // TODO(BT) there might be a small gap during STATE_TURNING_ON that 480 // mService is null, handle that case 481 } 482 } catch (RemoteException e) {Log.e(TAG, "", e);} 483 if (DBG) Log.d(TAG, "" + hashCode() + ": getState() : mService = null. Returning STATE_OFF"); 484 return STATE_OFF; 485 } 486 487 /** 488 * Turn on the local Bluetooth adapter—do not use without explicit 489 * user action to turn on Bluetooth. 490 * <p>This powers on the underlying Bluetooth hardware, and starts all 491 * Bluetooth system services. 492 * <p class="caution"><strong>Bluetooth should never be enabled without 493 * direct user consent</strong>. If you want to turn on Bluetooth in order 494 * to create a wireless connection, you should use the {@link 495 * #ACTION_REQUEST_ENABLE} Intent, which will raise a dialog that requests 496 * user permission to turn on Bluetooth. The {@link #enable()} method is 497 * provided only for applications that include a user interface for changing 498 * system settings, such as a "power manager" app.</p> 499 * <p>This is an asynchronous call: it will return immediately, and 500 * clients should listen for {@link #ACTION_STATE_CHANGED} 501 * to be notified of subsequent adapter state changes. If this call returns 502 * true, then the adapter state will immediately transition from {@link 503 * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time 504 * later transition to either {@link #STATE_OFF} or {@link 505 * #STATE_ON}. If this call returns false then there was an 506 * immediate problem that will prevent the adapter from being turned on - 507 * such as Airplane mode, or the adapter is already turned on. 508 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 509 * permission 510 * 511 * @return true to indicate adapter startup has begun, or false on 512 * immediate error 513 */ 514 public boolean enable() { 515 if (isEnabled() == true){ 516 if (DBG) Log.d(TAG, "enable(): BT is already enabled..!"); 517 return true; 518 } 519 try { 520 return mManagerService.enable(); 521 } catch (RemoteException e) {Log.e(TAG, "", e);} 522 return false; 523 } 524 525 /** 526 * Turn off the local Bluetooth adapter—do not use without explicit 527 * user action to turn off Bluetooth. 528 * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth 529 * system services, and powers down the underlying Bluetooth hardware. 530 * <p class="caution"><strong>Bluetooth should never be disabled without 531 * direct user consent</strong>. The {@link #disable()} method is 532 * provided only for applications that include a user interface for changing 533 * system settings, such as a "power manager" app.</p> 534 * <p>This is an asynchronous call: it will return immediately, and 535 * clients should listen for {@link #ACTION_STATE_CHANGED} 536 * to be notified of subsequent adapter state changes. If this call returns 537 * true, then the adapter state will immediately transition from {@link 538 * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time 539 * later transition to either {@link #STATE_OFF} or {@link 540 * #STATE_ON}. If this call returns false then there was an 541 * immediate problem that will prevent the adapter from being turned off - 542 * such as the adapter already being turned off. 543 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 544 * permission 545 * 546 * @return true to indicate adapter shutdown has begun, or false on 547 * immediate error 548 */ 549 public boolean disable() { 550 try { 551 return mManagerService.disable(true); 552 } catch (RemoteException e) {Log.e(TAG, "", e);} 553 return false; 554 } 555 556 /** 557 * Turn off the local Bluetooth adapter and don't persist the setting. 558 * 559 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 560 * permission 561 * 562 * @return true to indicate adapter shutdown has begun, or false on 563 * immediate error 564 * @hide 565 */ 566 public boolean disable(boolean persist) { 567 568 try { 569 return mManagerService.disable(persist); 570 } catch (RemoteException e) {Log.e(TAG, "", e);} 571 return false; 572 } 573 574 /** 575 * Returns the hardware address of the local Bluetooth adapter. 576 * <p>For example, "00:11:22:AA:BB:CC". 577 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 578 * 579 * @return Bluetooth hardware address as string 580 */ 581 public String getAddress() { 582 try { 583 return mManagerService.getAddress(); 584 } catch (RemoteException e) {Log.e(TAG, "", e);} 585 return null; 586 } 587 588 /** 589 * Get the friendly Bluetooth name of the local Bluetooth adapter. 590 * <p>This name is visible to remote Bluetooth devices. 591 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 592 * 593 * @return the Bluetooth name, or null on error 594 */ 595 public String getName() { 596 try { 597 return mManagerService.getName(); 598 } catch (RemoteException e) {Log.e(TAG, "", e);} 599 return null; 600 } 601 602 /** 603 * enable or disable Bluetooth HCI snoop log. 604 * 605 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 606 * permission 607 * 608 * @return true to indicate configure HCI log successfully, or false on 609 * immediate error 610 * @hide 611 */ 612 public boolean configHciSnoopLog(boolean enable) { 613 try { 614 synchronized(mManagerCallback) { 615 if (mService != null) return mService.configHciSnoopLog(enable); 616 } 617 } catch (RemoteException e) {Log.e(TAG, "", e);} 618 return false; 619 } 620 621 /** 622 * Get the UUIDs supported by the local Bluetooth adapter. 623 * 624 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 625 * 626 * @return the UUIDs supported by the local Bluetooth Adapter. 627 * @hide 628 */ 629 public ParcelUuid[] getUuids() { 630 if (getState() != STATE_ON) return null; 631 try { 632 synchronized(mManagerCallback) { 633 if (mService != null) return mService.getUuids(); 634 } 635 } catch (RemoteException e) {Log.e(TAG, "", e);} 636 return null; 637 } 638 639 /** 640 * Set the friendly Bluetooth name of the local Bluetooth adapter. 641 * <p>This name is visible to remote Bluetooth devices. 642 * <p>Valid Bluetooth names are a maximum of 248 bytes using UTF-8 643 * encoding, although many remote devices can only display the first 644 * 40 characters, and some may be limited to just 20. 645 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 646 * will return false. After turning on Bluetooth, 647 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 648 * to get the updated value. 649 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} 650 * 651 * @param name a valid Bluetooth name 652 * @return true if the name was set, false otherwise 653 */ 654 public boolean setName(String name) { 655 if (getState() != STATE_ON) return false; 656 try { 657 synchronized(mManagerCallback) { 658 if (mService != null) return mService.setName(name); 659 } 660 } catch (RemoteException e) {Log.e(TAG, "", e);} 661 return false; 662 } 663 664 /** 665 * Get the current Bluetooth scan mode of the local Bluetooth adapter. 666 * <p>The Bluetooth scan mode determines if the local adapter is 667 * connectable and/or discoverable from remote Bluetooth devices. 668 * <p>Possible values are: 669 * {@link #SCAN_MODE_NONE}, 670 * {@link #SCAN_MODE_CONNECTABLE}, 671 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. 672 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 673 * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth, 674 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 675 * to get the updated value. 676 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 677 * 678 * @return scan mode 679 */ 680 public int getScanMode() { 681 if (getState() != STATE_ON) return SCAN_MODE_NONE; 682 try { 683 synchronized(mManagerCallback) { 684 if (mService != null) return mService.getScanMode(); 685 } 686 } catch (RemoteException e) {Log.e(TAG, "", e);} 687 return SCAN_MODE_NONE; 688 } 689 690 /** 691 * Set the Bluetooth scan mode of the local Bluetooth adapter. 692 * <p>The Bluetooth scan mode determines if the local adapter is 693 * connectable and/or discoverable from remote Bluetooth devices. 694 * <p>For privacy reasons, discoverable mode is automatically turned off 695 * after <code>duration</code> seconds. For example, 120 seconds should be 696 * enough for a remote device to initiate and complete its discovery 697 * process. 698 * <p>Valid scan mode values are: 699 * {@link #SCAN_MODE_NONE}, 700 * {@link #SCAN_MODE_CONNECTABLE}, 701 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. 702 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 703 * will return false. After turning on Bluetooth, 704 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 705 * to get the updated value. 706 * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} 707 * <p>Applications cannot set the scan mode. They should use 708 * <code>startActivityForResult( 709 * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE}) 710 * </code>instead. 711 * 712 * @param mode valid scan mode 713 * @param duration time in seconds to apply scan mode, only used for 714 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE} 715 * @return true if the scan mode was set, false otherwise 716 * @hide 717 */ 718 public boolean setScanMode(int mode, int duration) { 719 if (getState() != STATE_ON) return false; 720 try { 721 synchronized(mManagerCallback) { 722 if (mService != null) return mService.setScanMode(mode, duration); 723 } 724 } catch (RemoteException e) {Log.e(TAG, "", e);} 725 return false; 726 } 727 728 /** @hide */ 729 public boolean setScanMode(int mode) { 730 if (getState() != STATE_ON) return false; 731 /* getDiscoverableTimeout() to use the latest from NV than use 0 */ 732 return setScanMode(mode, getDiscoverableTimeout()); 733 } 734 735 /** @hide */ 736 public int getDiscoverableTimeout() { 737 if (getState() != STATE_ON) return -1; 738 try { 739 synchronized(mManagerCallback) { 740 if (mService != null) return mService.getDiscoverableTimeout(); 741 } 742 } catch (RemoteException e) {Log.e(TAG, "", e);} 743 return -1; 744 } 745 746 /** @hide */ 747 public void setDiscoverableTimeout(int timeout) { 748 if (getState() != STATE_ON) return; 749 try { 750 synchronized(mManagerCallback) { 751 if (mService != null) mService.setDiscoverableTimeout(timeout); 752 } 753 } catch (RemoteException e) {Log.e(TAG, "", e);} 754 } 755 756 /** 757 * Start the remote device discovery process. 758 * <p>The discovery process usually involves an inquiry scan of about 12 759 * seconds, followed by a page scan of each new device to retrieve its 760 * Bluetooth name. 761 * <p>This is an asynchronous call, it will return immediately. Register 762 * for {@link #ACTION_DISCOVERY_STARTED} and {@link 763 * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the 764 * discovery starts and completes. Register for {@link 765 * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices 766 * are found. 767 * <p>Device discovery is a heavyweight procedure. New connections to 768 * remote Bluetooth devices should not be attempted while discovery is in 769 * progress, and existing connections will experience limited bandwidth 770 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 771 * discovery. Discovery is not managed by the Activity, 772 * but is run as a system service, so an application should always call 773 * {@link BluetoothAdapter#cancelDiscovery()} even if it 774 * did not directly request a discovery, just to be sure. 775 * <p>Device discovery will only find remote devices that are currently 776 * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are 777 * not discoverable by default, and need to be entered into a special mode. 778 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 779 * will return false. After turning on Bluetooth, 780 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 781 * to get the updated value. 782 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}. 783 * 784 * @return true on success, false on error 785 */ 786 public boolean startDiscovery() { 787 if (getState() != STATE_ON) return false; 788 try { 789 synchronized(mManagerCallback) { 790 if (mService != null) return mService.startDiscovery(); 791 } 792 } catch (RemoteException e) {Log.e(TAG, "", e);} 793 return false; 794 } 795 796 /** 797 * Cancel the current device discovery process. 798 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}. 799 * <p>Because discovery is a heavyweight procedure for the Bluetooth 800 * adapter, this method should always be called before attempting to connect 801 * to a remote device with {@link 802 * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by 803 * the Activity, but is run as a system service, so an application should 804 * always call cancel discovery even if it did not directly request a 805 * discovery, just to be sure. 806 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 807 * will return false. After turning on Bluetooth, 808 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 809 * to get the updated value. 810 * 811 * @return true on success, false on error 812 */ 813 public boolean cancelDiscovery() { 814 if (getState() != STATE_ON) return false; 815 try { 816 synchronized(mManagerCallback) { 817 if (mService != null) return mService.cancelDiscovery(); 818 } 819 } catch (RemoteException e) {Log.e(TAG, "", e);} 820 return false; 821 } 822 823 /** 824 * Return true if the local Bluetooth adapter is currently in the device 825 * discovery process. 826 * <p>Device discovery is a heavyweight procedure. New connections to 827 * remote Bluetooth devices should not be attempted while discovery is in 828 * progress, and existing connections will experience limited bandwidth 829 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 830 * discovery. 831 * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED} 832 * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery 833 * starts or completes. 834 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 835 * will return false. After turning on Bluetooth, 836 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 837 * to get the updated value. 838 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 839 * 840 * @return true if discovering 841 */ 842 public boolean isDiscovering() { 843 if (getState() != STATE_ON) return false; 844 try { 845 synchronized(mManagerCallback) { 846 if (mService != null ) return mService.isDiscovering(); 847 } 848 } catch (RemoteException e) {Log.e(TAG, "", e);} 849 return false; 850 } 851 852 /** 853 * Return the set of {@link BluetoothDevice} objects that are bonded 854 * (paired) to the local adapter. 855 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 856 * will return an empty set. After turning on Bluetooth, 857 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 858 * to get the updated value. 859 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 860 * 861 * @return unmodifiable set of {@link BluetoothDevice}, or null on error 862 */ 863 public Set<BluetoothDevice> getBondedDevices() { 864 if (getState() != STATE_ON) { 865 return toDeviceSet(new BluetoothDevice[0]); 866 } 867 try { 868 synchronized(mManagerCallback) { 869 if (mService != null) return toDeviceSet(mService.getBondedDevices()); 870 } 871 return toDeviceSet(new BluetoothDevice[0]); 872 } catch (RemoteException e) {Log.e(TAG, "", e);} 873 return null; 874 } 875 876 /** 877 * Get the current connection state of the local Bluetooth adapter. 878 * This can be used to check whether the local Bluetooth adapter is connected 879 * to any profile of any other remote Bluetooth Device. 880 * 881 * <p> Use this function along with {@link #ACTION_CONNECTION_STATE_CHANGED} 882 * intent to get the connection state of the adapter. 883 * 884 * @return One of {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTED}, 885 * {@link #STATE_CONNECTING} or {@link #STATE_DISCONNECTED} 886 * 887 * @hide 888 */ 889 public int getConnectionState() { 890 if (getState() != STATE_ON) return BluetoothAdapter.STATE_DISCONNECTED; 891 try { 892 synchronized(mManagerCallback) { 893 if (mService != null) return mService.getAdapterConnectionState(); 894 } 895 } catch (RemoteException e) {Log.e(TAG, "getConnectionState:", e);} 896 return BluetoothAdapter.STATE_DISCONNECTED; 897 } 898 899 /** 900 * Get the current connection state of a profile. 901 * This function can be used to check whether the local Bluetooth adapter 902 * is connected to any remote device for a specific profile. 903 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET}, 904 * {@link BluetoothProfile#A2DP}. 905 * 906 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 907 * 908 * <p> Return value can be one of 909 * {@link BluetoothProfile#STATE_DISCONNECTED}, 910 * {@link BluetoothProfile#STATE_CONNECTING}, 911 * {@link BluetoothProfile#STATE_CONNECTED}, 912 * {@link BluetoothProfile#STATE_DISCONNECTING} 913 */ 914 public int getProfileConnectionState(int profile) { 915 if (getState() != STATE_ON) return BluetoothProfile.STATE_DISCONNECTED; 916 try { 917 synchronized(mManagerCallback) { 918 if (mService != null) return mService.getProfileConnectionState(profile); 919 } 920 } catch (RemoteException e) { 921 Log.e(TAG, "getProfileConnectionState:", e); 922 } 923 return BluetoothProfile.STATE_DISCONNECTED; 924 } 925 926 /** 927 * Create a listening, secure RFCOMM Bluetooth socket. 928 * <p>A remote device connecting to this socket will be authenticated and 929 * communication on this socket will be encrypted. 930 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 931 * connections from a listening {@link BluetoothServerSocket}. 932 * <p>Valid RFCOMM channels are in range 1 to 30. 933 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} 934 * @param channel RFCOMM channel to listen on 935 * @return a listening RFCOMM BluetoothServerSocket 936 * @throws IOException on error, for example Bluetooth not available, or 937 * insufficient permissions, or channel in use. 938 * @hide 939 */ 940 public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException { 941 BluetoothServerSocket socket = new BluetoothServerSocket( 942 BluetoothSocket.TYPE_RFCOMM, true, true, channel); 943 int errno = socket.mSocket.bindListen(); 944 if (errno != 0) { 945 //TODO(BT): Throw the same exception error code 946 // that the previous code was using. 947 //socket.mSocket.throwErrnoNative(errno); 948 throw new IOException("Error: " + errno); 949 } 950 return socket; 951 } 952 953 /** 954 * Create a listening, secure RFCOMM Bluetooth socket with Service Record. 955 * <p>A remote device connecting to this socket will be authenticated and 956 * communication on this socket will be encrypted. 957 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 958 * connections from a listening {@link BluetoothServerSocket}. 959 * <p>The system will assign an unused RFCOMM channel to listen on. 960 * <p>The system will also register a Service Discovery 961 * Protocol (SDP) record with the local SDP server containing the specified 962 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 963 * can use the same UUID to query our SDP server and discover which channel 964 * to connect to. This SDP record will be removed when this socket is 965 * closed, or if this application closes unexpectedly. 966 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 967 * connect to this socket from another device using the same {@link UUID}. 968 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 969 * @param name service name for SDP record 970 * @param uuid uuid for SDP record 971 * @return a listening RFCOMM BluetoothServerSocket 972 * @throws IOException on error, for example Bluetooth not available, or 973 * insufficient permissions, or channel in use. 974 */ 975 public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid) 976 throws IOException { 977 return createNewRfcommSocketAndRecord(name, uuid, true, true); 978 } 979 980 /** 981 * Create a listening, insecure RFCOMM Bluetooth socket with Service Record. 982 * <p>The link key is not required to be authenticated, i.e the communication may be 983 * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices, 984 * the link will be encrypted, as encryption is mandartory. 985 * For legacy devices (pre Bluetooth 2.1 devices) the link will not 986 * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an 987 * encrypted and authenticated communication channel is desired. 988 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 989 * connections from a listening {@link BluetoothServerSocket}. 990 * <p>The system will assign an unused RFCOMM channel to listen on. 991 * <p>The system will also register a Service Discovery 992 * Protocol (SDP) record with the local SDP server containing the specified 993 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 994 * can use the same UUID to query our SDP server and discover which channel 995 * to connect to. This SDP record will be removed when this socket is 996 * closed, or if this application closes unexpectedly. 997 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 998 * connect to this socket from another device using the same {@link UUID}. 999 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1000 * @param name service name for SDP record 1001 * @param uuid uuid for SDP record 1002 * @return a listening RFCOMM BluetoothServerSocket 1003 * @throws IOException on error, for example Bluetooth not available, or 1004 * insufficient permissions, or channel in use. 1005 */ 1006 public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid) 1007 throws IOException { 1008 return createNewRfcommSocketAndRecord(name, uuid, false, false); 1009 } 1010 1011 /** 1012 * Create a listening, encrypted, 1013 * RFCOMM Bluetooth socket with Service Record. 1014 * <p>The link will be encrypted, but the link key is not required to be authenticated 1015 * i.e the communication is vulnerable to Man In the Middle attacks. Use 1016 * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key. 1017 * <p> Use this socket if authentication of link key is not possible. 1018 * For example, for Bluetooth 2.1 devices, if any of the devices does not have 1019 * an input and output capability or just has the ability to display a numeric key, 1020 * a secure socket connection is not possible and this socket can be used. 1021 * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required. 1022 * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory. 1023 * For more details, refer to the Security Model section 5.2 (vol 3) of 1024 * Bluetooth Core Specification version 2.1 + EDR. 1025 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 1026 * connections from a listening {@link BluetoothServerSocket}. 1027 * <p>The system will assign an unused RFCOMM channel to listen on. 1028 * <p>The system will also register a Service Discovery 1029 * Protocol (SDP) record with the local SDP server containing the specified 1030 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 1031 * can use the same UUID to query our SDP server and discover which channel 1032 * to connect to. This SDP record will be removed when this socket is 1033 * closed, or if this application closes unexpectedly. 1034 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 1035 * connect to this socket from another device using the same {@link UUID}. 1036 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1037 * @param name service name for SDP record 1038 * @param uuid uuid for SDP record 1039 * @return a listening RFCOMM BluetoothServerSocket 1040 * @throws IOException on error, for example Bluetooth not available, or 1041 * insufficient permissions, or channel in use. 1042 * @hide 1043 */ 1044 public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord( 1045 String name, UUID uuid) throws IOException { 1046 return createNewRfcommSocketAndRecord(name, uuid, false, true); 1047 } 1048 1049 1050 private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid, 1051 boolean auth, boolean encrypt) throws IOException { 1052 BluetoothServerSocket socket; 1053 socket = new BluetoothServerSocket(BluetoothSocket.TYPE_RFCOMM, auth, 1054 encrypt, new ParcelUuid(uuid)); 1055 socket.setServiceName(name); 1056 int errno = socket.mSocket.bindListen(); 1057 if (errno != 0) { 1058 //TODO(BT): Throw the same exception error code 1059 // that the previous code was using. 1060 //socket.mSocket.throwErrnoNative(errno); 1061 throw new IOException("Error: " + errno); 1062 } 1063 return socket; 1064 } 1065 1066 /** 1067 * Construct an unencrypted, unauthenticated, RFCOMM server socket. 1068 * Call #accept to retrieve connections to this socket. 1069 * @return An RFCOMM BluetoothServerSocket 1070 * @throws IOException On error, for example Bluetooth not available, or 1071 * insufficient permissions. 1072 * @hide 1073 */ 1074 public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException { 1075 BluetoothServerSocket socket = new BluetoothServerSocket( 1076 BluetoothSocket.TYPE_RFCOMM, false, false, port); 1077 int errno = socket.mSocket.bindListen(); 1078 if (errno != 0) { 1079 //TODO(BT): Throw the same exception error code 1080 // that the previous code was using. 1081 //socket.mSocket.throwErrnoNative(errno); 1082 throw new IOException("Error: " + errno); 1083 } 1084 return socket; 1085 } 1086 1087 /** 1088 * Construct an encrypted, RFCOMM server socket. 1089 * Call #accept to retrieve connections to this socket. 1090 * @return An RFCOMM BluetoothServerSocket 1091 * @throws IOException On error, for example Bluetooth not available, or 1092 * insufficient permissions. 1093 * @hide 1094 */ 1095 public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port) 1096 throws IOException { 1097 BluetoothServerSocket socket = new BluetoothServerSocket( 1098 BluetoothSocket.TYPE_RFCOMM, false, true, port); 1099 int errno = socket.mSocket.bindListen(); 1100 if (errno < 0) { 1101 //TODO(BT): Throw the same exception error code 1102 // that the previous code was using. 1103 //socket.mSocket.throwErrnoNative(errno); 1104 throw new IOException("Error: " + errno); 1105 } 1106 return socket; 1107 } 1108 1109 /** 1110 * Construct a SCO server socket. 1111 * Call #accept to retrieve connections to this socket. 1112 * @return A SCO BluetoothServerSocket 1113 * @throws IOException On error, for example Bluetooth not available, or 1114 * insufficient permissions. 1115 * @hide 1116 */ 1117 public static BluetoothServerSocket listenUsingScoOn() throws IOException { 1118 BluetoothServerSocket socket = new BluetoothServerSocket( 1119 BluetoothSocket.TYPE_SCO, false, false, -1); 1120 int errno = socket.mSocket.bindListen(); 1121 if (errno < 0) { 1122 //TODO(BT): Throw the same exception error code 1123 // that the previous code was using. 1124 //socket.mSocket.throwErrnoNative(errno); 1125 } 1126 return socket; 1127 } 1128 1129 /** 1130 * Read the local Out of Band Pairing Data 1131 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1132 * 1133 * @return Pair<byte[], byte[]> of Hash and Randomizer 1134 * 1135 * @hide 1136 */ 1137 public Pair<byte[], byte[]> readOutOfBandData() { 1138 if (getState() != STATE_ON) return null; 1139 //TODO(BT 1140 /* 1141 try { 1142 byte[] hash; 1143 byte[] randomizer; 1144 1145 byte[] ret = mService.readOutOfBandData(); 1146 1147 if (ret == null || ret.length != 32) return null; 1148 1149 hash = Arrays.copyOfRange(ret, 0, 16); 1150 randomizer = Arrays.copyOfRange(ret, 16, 32); 1151 1152 if (DBG) { 1153 Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) + 1154 ":" + Arrays.toString(randomizer)); 1155 } 1156 return new Pair<byte[], byte[]>(hash, randomizer); 1157 1158 } catch (RemoteException e) {Log.e(TAG, "", e);}*/ 1159 return null; 1160 } 1161 1162 /** 1163 * Get the profile proxy object associated with the profile. 1164 * 1165 * <p>Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET}, 1166 * {@link BluetoothProfile#A2DP}, {@link BluetoothProfile#GATT}, or 1167 * {@link BluetoothProfile#GATT_SERVER}. Clients must implement 1168 * {@link BluetoothProfile.ServiceListener} to get notified of 1169 * the connection status and to get the proxy object. 1170 * 1171 * @param context Context of the application 1172 * @param listener The service Listener for connection callbacks. 1173 * @param profile The Bluetooth profile; either {@link BluetoothProfile#HEALTH}, 1174 * {@link BluetoothProfile#HEADSET} or {@link BluetoothProfile#A2DP}. 1175 * @return true on success, false on error 1176 */ 1177 public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener, 1178 int profile) { 1179 if (context == null || listener == null) return false; 1180 1181 if (profile == BluetoothProfile.HEADSET) { 1182 BluetoothHeadset headset = new BluetoothHeadset(context, listener); 1183 return true; 1184 } else if (profile == BluetoothProfile.A2DP) { 1185 BluetoothA2dp a2dp = new BluetoothA2dp(context, listener); 1186 return true; 1187 } else if (profile == BluetoothProfile.INPUT_DEVICE) { 1188 BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener); 1189 return true; 1190 } else if (profile == BluetoothProfile.PAN) { 1191 BluetoothPan pan = new BluetoothPan(context, listener); 1192 return true; 1193 } else if (profile == BluetoothProfile.HEALTH) { 1194 BluetoothHealth health = new BluetoothHealth(context, listener); 1195 return true; 1196 } else { 1197 return false; 1198 } 1199 } 1200 1201 /** 1202 * Close the connection of the profile proxy to the Service. 1203 * 1204 * <p> Clients should call this when they are no longer using 1205 * the proxy obtained from {@link #getProfileProxy}. 1206 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or 1207 * {@link BluetoothProfile#A2DP} 1208 * 1209 * @param profile 1210 * @param proxy Profile proxy object 1211 */ 1212 public void closeProfileProxy(int profile, BluetoothProfile proxy) { 1213 if (proxy == null) return; 1214 1215 switch (profile) { 1216 case BluetoothProfile.HEADSET: 1217 BluetoothHeadset headset = (BluetoothHeadset)proxy; 1218 headset.close(); 1219 break; 1220 case BluetoothProfile.A2DP: 1221 BluetoothA2dp a2dp = (BluetoothA2dp)proxy; 1222 a2dp.close(); 1223 break; 1224 case BluetoothProfile.INPUT_DEVICE: 1225 BluetoothInputDevice iDev = (BluetoothInputDevice)proxy; 1226 iDev.close(); 1227 break; 1228 case BluetoothProfile.PAN: 1229 BluetoothPan pan = (BluetoothPan)proxy; 1230 pan.close(); 1231 break; 1232 case BluetoothProfile.HEALTH: 1233 BluetoothHealth health = (BluetoothHealth)proxy; 1234 health.close(); 1235 break; 1236 case BluetoothProfile.GATT: 1237 BluetoothGatt gatt = (BluetoothGatt)proxy; 1238 gatt.close(); 1239 break; 1240 case BluetoothProfile.GATT_SERVER: 1241 BluetoothGattServer gattServer = (BluetoothGattServer)proxy; 1242 gattServer.close(); 1243 break; 1244 } 1245 } 1246 1247 final private IBluetoothManagerCallback mManagerCallback = 1248 new IBluetoothManagerCallback.Stub() { 1249 public void onBluetoothServiceUp(IBluetooth bluetoothService) { 1250 if (VDBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService); 1251 synchronized (mManagerCallback) { 1252 mService = bluetoothService; 1253 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){ 1254 try { 1255 if (cb != null) { 1256 cb.onBluetoothServiceUp(bluetoothService); 1257 } else { 1258 Log.d(TAG, "onBluetoothServiceUp: cb is null!!!"); 1259 } 1260 } catch (Exception e) { Log.e(TAG,"",e);} 1261 } 1262 } 1263 } 1264 1265 public void onBluetoothServiceDown() { 1266 if (VDBG) Log.d(TAG, "onBluetoothServiceDown: " + mService); 1267 synchronized (mManagerCallback) { 1268 mService = null; 1269 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){ 1270 try { 1271 if (cb != null) { 1272 cb.onBluetoothServiceDown(); 1273 } else { 1274 Log.d(TAG, "onBluetoothServiceDown: cb is null!!!"); 1275 } 1276 } catch (Exception e) { Log.e(TAG,"",e);} 1277 } 1278 } 1279 } 1280 }; 1281 1282 /** 1283 * Enable the Bluetooth Adapter, but don't auto-connect devices 1284 * and don't persist state. Only for use by system applications. 1285 * @hide 1286 */ 1287 public boolean enableNoAutoConnect() { 1288 if (isEnabled() == true){ 1289 if (DBG) Log.d(TAG, "enableNoAutoConnect(): BT is already enabled..!"); 1290 return true; 1291 } 1292 try { 1293 return mManagerService.enableNoAutoConnect(); 1294 } catch (RemoteException e) {Log.e(TAG, "", e);} 1295 return false; 1296 } 1297 1298 /** 1299 * Enable control of the Bluetooth Adapter for a single application. 1300 * 1301 * <p>Some applications need to use Bluetooth for short periods of time to 1302 * transfer data but don't want all the associated implications like 1303 * automatic connection to headsets etc. 1304 * 1305 * <p> Multiple applications can call this. This is reference counted and 1306 * Bluetooth disabled only when no one else is using it. There will be no UI 1307 * shown to the user while bluetooth is being enabled. Any user action will 1308 * override this call. For example, if user wants Bluetooth on and the last 1309 * user of this API wanted to disable Bluetooth, Bluetooth will not be 1310 * turned off. 1311 * 1312 * <p> This API is only meant to be used by internal applications. Third 1313 * party applications but use {@link #enable} and {@link #disable} APIs. 1314 * 1315 * <p> If this API returns true, it means the callback will be called. 1316 * The callback will be called with the current state of Bluetooth. 1317 * If the state is not what was requested, an internal error would be the 1318 * reason. If Bluetooth is already on and if this function is called to turn 1319 * it on, the api will return true and a callback will be called. 1320 * 1321 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1322 * 1323 * @param on True for on, false for off. 1324 * @param callback The callback to notify changes to the state. 1325 * @hide 1326 */ 1327 public boolean changeApplicationBluetoothState(boolean on, 1328 BluetoothStateChangeCallback callback) { 1329 if (callback == null) return false; 1330 1331 //TODO(BT) 1332 /* 1333 try { 1334 return mService.changeApplicationBluetoothState(on, new 1335 StateChangeCallbackWrapper(callback), new Binder()); 1336 } catch (RemoteException e) { 1337 Log.e(TAG, "changeBluetoothState", e); 1338 }*/ 1339 return false; 1340 } 1341 1342 /** 1343 * @hide 1344 */ 1345 public interface BluetoothStateChangeCallback { 1346 public void onBluetoothStateChange(boolean on); 1347 } 1348 1349 /** 1350 * @hide 1351 */ 1352 public class StateChangeCallbackWrapper extends IBluetoothStateChangeCallback.Stub { 1353 private BluetoothStateChangeCallback mCallback; 1354 1355 StateChangeCallbackWrapper(BluetoothStateChangeCallback 1356 callback) { 1357 mCallback = callback; 1358 } 1359 1360 @Override 1361 public void onBluetoothStateChange(boolean on) { 1362 mCallback.onBluetoothStateChange(on); 1363 } 1364 } 1365 1366 private Set<BluetoothDevice> toDeviceSet(BluetoothDevice[] devices) { 1367 Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(Arrays.asList(devices)); 1368 return Collections.unmodifiableSet(deviceSet); 1369 } 1370 1371 protected void finalize() throws Throwable { 1372 try { 1373 mManagerService.unregisterAdapter(mManagerCallback); 1374 } catch (RemoteException e) { 1375 Log.e(TAG, "", e); 1376 } finally { 1377 super.finalize(); 1378 } 1379 } 1380 1381 1382 /** 1383 * Validate a String Bluetooth address, such as "00:43:A8:23:10:F0" 1384 * <p>Alphabetic characters must be uppercase to be valid. 1385 * 1386 * @param address Bluetooth address as string 1387 * @return true if the address is valid, false otherwise 1388 */ 1389 public static boolean checkBluetoothAddress(String address) { 1390 if (address == null || address.length() != ADDRESS_LENGTH) { 1391 return false; 1392 } 1393 for (int i = 0; i < ADDRESS_LENGTH; i++) { 1394 char c = address.charAt(i); 1395 switch (i % 3) { 1396 case 0: 1397 case 1: 1398 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) { 1399 // hex character, OK 1400 break; 1401 } 1402 return false; 1403 case 2: 1404 if (c == ':') { 1405 break; // OK 1406 } 1407 return false; 1408 } 1409 } 1410 return true; 1411 } 1412 1413 /*package*/ IBluetoothManager getBluetoothManager() { 1414 return mManagerService; 1415 } 1416 1417 private ArrayList<IBluetoothManagerCallback> mProxyServiceStateCallbacks = new ArrayList<IBluetoothManagerCallback>(); 1418 1419 /*package*/ IBluetooth getBluetoothService(IBluetoothManagerCallback cb) { 1420 synchronized (mManagerCallback) { 1421 if (cb == null) { 1422 Log.w(TAG, "getBluetoothService() called with no BluetoothManagerCallback"); 1423 } else if (!mProxyServiceStateCallbacks.contains(cb)) { 1424 mProxyServiceStateCallbacks.add(cb); 1425 } 1426 } 1427 return mService; 1428 } 1429 1430 /*package*/ void removeServiceStateCallback(IBluetoothManagerCallback cb) { 1431 synchronized (mManagerCallback) { 1432 mProxyServiceStateCallbacks.remove(cb); 1433 } 1434 } 1435 1436 /** 1437 * Callback interface used to deliver LE scan results. 1438 * 1439 * @see #startLeScan(LeScanCallback) 1440 * @see #startLeScan(UUID[], LeScanCallback) 1441 */ 1442 public interface LeScanCallback { 1443 /** 1444 * Callback reporting an LE device found during a device scan initiated 1445 * by the {@link BluetoothAdapter#startLeScan} function. 1446 * 1447 * @param device Identifies the remote device 1448 * @param rssi The RSSI value for the remote device as reported by the 1449 * Bluetooth hardware. 0 if no RSSI value is available. 1450 * @param scanRecord The content of the advertisement record offered by 1451 * the remote device. 1452 */ 1453 public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord); 1454 } 1455 1456 /** 1457 * Starts a scan for Bluetooth LE devices. 1458 * 1459 * <p>Results of the scan are reported using the 1460 * {@link LeScanCallback#onLeScan} callback. 1461 * 1462 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission. 1463 * 1464 * @param callback the callback LE scan results are delivered 1465 * @return true, if the scan was started successfully 1466 */ 1467 public boolean startLeScan(LeScanCallback callback) { 1468 return startLeScan(null, callback); 1469 } 1470 1471 /** 1472 * Starts a scan for Bluetooth LE devices, looking for devices that 1473 * advertise given services. 1474 * 1475 * <p>Devices which advertise all specified services are reported using the 1476 * {@link LeScanCallback#onLeScan} callback. 1477 * 1478 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission. 1479 * 1480 * @param serviceUuids Array of services to look for 1481 * @param callback the callback LE scan results are delivered 1482 * @return true, if the scan was started successfully 1483 */ 1484 public boolean startLeScan(UUID[] serviceUuids, LeScanCallback callback) { 1485 if (DBG) Log.d(TAG, "startLeScan(): " + serviceUuids); 1486 1487 if (callback == null) { 1488 if (DBG) Log.e(TAG, "startLeScan: null callback"); 1489 return false; 1490 } 1491 1492 synchronized(mLeScanClients) { 1493 if (mLeScanClients.containsKey(callback)) { 1494 if (DBG) Log.e(TAG, "LE Scan has already started"); 1495 return false; 1496 } 1497 1498 try { 1499 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt(); 1500 if (iGatt == null) { 1501 // BLE is not supported 1502 return false; 1503 } 1504 1505 UUID uuid = UUID.randomUUID(); 1506 GattCallbackWrapper wrapper = new GattCallbackWrapper(this, callback, serviceUuids); 1507 iGatt.registerClient(new ParcelUuid(uuid), wrapper); 1508 if (wrapper.scanStarted()) { 1509 mLeScanClients.put(callback, wrapper); 1510 return true; 1511 } 1512 } catch (RemoteException e) { 1513 Log.e(TAG,"",e); 1514 } 1515 } 1516 return false; 1517 } 1518 1519 /** 1520 * Stops an ongoing Bluetooth LE device scan. 1521 * 1522 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission. 1523 * 1524 * @param callback used to identify which scan to stop 1525 * must be the same handle used to start the scan 1526 */ 1527 public void stopLeScan(LeScanCallback callback) { 1528 if (DBG) Log.d(TAG, "stopLeScan()"); 1529 GattCallbackWrapper wrapper; 1530 synchronized(mLeScanClients) { 1531 wrapper = mLeScanClients.remove(callback); 1532 if (wrapper == null) return; 1533 } 1534 wrapper.stopLeScan(); 1535 } 1536 1537 /** 1538 * Bluetooth GATT interface callbacks 1539 */ 1540 private static class GattCallbackWrapper extends IBluetoothGattCallback.Stub { 1541 private static final int LE_CALLBACK_REG_TIMEOUT = 2000; 1542 private static final int LE_CALLBACK_REG_WAIT_COUNT = 5; 1543 1544 private final LeScanCallback mLeScanCb; 1545 // mLeHandle 0: not registered 1546 // -1: scan stopped 1547 // >0: registered and scan started 1548 private int mLeHandle; 1549 private final UUID[] mScanFilter; 1550 private WeakReference<BluetoothAdapter> mBluetoothAdapter; 1551 1552 public GattCallbackWrapper(BluetoothAdapter bluetoothAdapter, 1553 LeScanCallback leScanCb, UUID[] uuid) { 1554 mBluetoothAdapter = new WeakReference<BluetoothAdapter>(bluetoothAdapter); 1555 mLeScanCb = leScanCb; 1556 mScanFilter = uuid; 1557 mLeHandle = 0; 1558 } 1559 1560 public boolean scanStarted() { 1561 boolean started = false; 1562 synchronized(this) { 1563 if (mLeHandle == -1) return false; 1564 1565 int count = 0; 1566 // wait for callback registration and LE scan to start 1567 while (mLeHandle == 0 && count < LE_CALLBACK_REG_WAIT_COUNT) { 1568 try { 1569 wait(LE_CALLBACK_REG_TIMEOUT); 1570 } catch (InterruptedException e) { 1571 Log.e(TAG, "Callback reg wait interrupted: " + e); 1572 } 1573 count++; 1574 } 1575 started = (mLeHandle > 0); 1576 } 1577 return started; 1578 } 1579 1580 public void stopLeScan() { 1581 synchronized(this) { 1582 if (mLeHandle <= 0) { 1583 Log.e(TAG, "Error state, mLeHandle: " + mLeHandle); 1584 return; 1585 } 1586 BluetoothAdapter adapter = mBluetoothAdapter.get(); 1587 if (adapter != null) { 1588 try { 1589 IBluetoothGatt iGatt = adapter.getBluetoothManager().getBluetoothGatt(); 1590 iGatt.stopScan(mLeHandle, false); 1591 iGatt.unregisterClient(mLeHandle); 1592 } catch (RemoteException e) { 1593 Log.e(TAG, "Failed to stop scan and unregister" + e); 1594 } 1595 } else { 1596 Log.e(TAG, "stopLeScan, BluetoothAdapter is null"); 1597 } 1598 mLeHandle = -1; 1599 notifyAll(); 1600 } 1601 } 1602 1603 /** 1604 * Application interface registered - app is ready to go 1605 */ 1606 public void onClientRegistered(int status, int clientIf) { 1607 if (DBG) Log.d(TAG, "onClientRegistered() - status=" + status + 1608 " clientIf=" + clientIf); 1609 synchronized(this) { 1610 if (mLeHandle == -1) { 1611 if (DBG) Log.d(TAG, "onClientRegistered LE scan canceled"); 1612 } 1613 1614 if (status == BluetoothGatt.GATT_SUCCESS) { 1615 mLeHandle = clientIf; 1616 IBluetoothGatt iGatt = null; 1617 try { 1618 BluetoothAdapter adapter = mBluetoothAdapter.get(); 1619 if (adapter != null) { 1620 iGatt = adapter.getBluetoothManager().getBluetoothGatt(); 1621 if (mScanFilter == null) { 1622 iGatt.startScan(mLeHandle, false); 1623 } else { 1624 ParcelUuid[] uuids = new ParcelUuid[mScanFilter.length]; 1625 for(int i = 0; i != uuids.length; ++i) { 1626 uuids[i] = new ParcelUuid(mScanFilter[i]); 1627 } 1628 iGatt.startScanWithUuids(mLeHandle, false, uuids); 1629 } 1630 } else { 1631 Log.e(TAG, "onClientRegistered, BluetoothAdapter null"); 1632 mLeHandle = -1; 1633 } 1634 } catch (RemoteException e) { 1635 Log.e(TAG, "fail to start le scan: " + e); 1636 mLeHandle = -1; 1637 } 1638 if (mLeHandle == -1) { 1639 // registration succeeded but start scan failed 1640 if (iGatt != null) { 1641 try { 1642 iGatt.unregisterClient(mLeHandle); 1643 } catch (RemoteException e) { 1644 Log.e(TAG, "fail to unregister callback: " + mLeHandle + 1645 " error: " + e); 1646 } 1647 } 1648 } 1649 } else { 1650 // registration failed 1651 mLeHandle = -1; 1652 } 1653 notifyAll(); 1654 } 1655 } 1656 1657 public void onClientConnectionState(int status, int clientIf, 1658 boolean connected, String address) { 1659 // no op 1660 } 1661 1662 /** 1663 * Callback reporting an LE scan result. 1664 * @hide 1665 */ 1666 public void onScanResult(String address, int rssi, byte[] advData) { 1667 if (DBG) Log.d(TAG, "onScanResult() - Device=" + address + " RSSI=" +rssi); 1668 1669 // Check null in case the scan has been stopped 1670 synchronized(this) { 1671 if (mLeHandle <= 0) return; 1672 } 1673 try { 1674 BluetoothAdapter adapter = mBluetoothAdapter.get(); 1675 if (adapter == null) { 1676 Log.d(TAG, "onScanResult, BluetoothAdapter null"); 1677 return; 1678 } 1679 mLeScanCb.onLeScan(adapter.getRemoteDevice(address), rssi, advData); 1680 } catch (Exception ex) { 1681 Log.w(TAG, "Unhandled exception: " + ex); 1682 } 1683 } 1684 1685 public void onGetService(String address, int srvcType, 1686 int srvcInstId, ParcelUuid srvcUuid) { 1687 // no op 1688 } 1689 1690 public void onGetIncludedService(String address, int srvcType, 1691 int srvcInstId, ParcelUuid srvcUuid, 1692 int inclSrvcType, int inclSrvcInstId, 1693 ParcelUuid inclSrvcUuid) { 1694 // no op 1695 } 1696 1697 public void onGetCharacteristic(String address, int srvcType, 1698 int srvcInstId, ParcelUuid srvcUuid, 1699 int charInstId, ParcelUuid charUuid, 1700 int charProps) { 1701 // no op 1702 } 1703 1704 public void onGetDescriptor(String address, int srvcType, 1705 int srvcInstId, ParcelUuid srvcUuid, 1706 int charInstId, ParcelUuid charUuid, 1707 ParcelUuid descUuid) { 1708 // no op 1709 } 1710 1711 public void onSearchComplete(String address, int status) { 1712 // no op 1713 } 1714 1715 public void onCharacteristicRead(String address, int status, int srvcType, 1716 int srvcInstId, ParcelUuid srvcUuid, 1717 int charInstId, ParcelUuid charUuid, byte[] value) { 1718 // no op 1719 } 1720 1721 public void onCharacteristicWrite(String address, int status, int srvcType, 1722 int srvcInstId, ParcelUuid srvcUuid, 1723 int charInstId, ParcelUuid charUuid) { 1724 // no op 1725 } 1726 1727 public void onNotify(String address, int srvcType, 1728 int srvcInstId, ParcelUuid srvcUuid, 1729 int charInstId, ParcelUuid charUuid, 1730 byte[] value) { 1731 // no op 1732 } 1733 1734 public void onDescriptorRead(String address, int status, int srvcType, 1735 int srvcInstId, ParcelUuid srvcUuid, 1736 int charInstId, ParcelUuid charUuid, 1737 ParcelUuid descrUuid, byte[] value) { 1738 // no op 1739 } 1740 1741 public void onDescriptorWrite(String address, int status, int srvcType, 1742 int srvcInstId, ParcelUuid srvcUuid, 1743 int charInstId, ParcelUuid charUuid, 1744 ParcelUuid descrUuid) { 1745 // no op 1746 } 1747 1748 public void onExecuteWrite(String address, int status) { 1749 // no op 1750 } 1751 1752 public void onReadRemoteRssi(String address, int rssi, int status) { 1753 // no op 1754 } 1755 } 1756 1757} 1758