BluetoothAdapter.java revision 0f42037eb7b5118015c2caca635538324ccf0ccf
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.Handler; 24import android.os.IBinder; 25import android.os.Looper; 26import android.os.Message; 27import android.os.ParcelUuid; 28import android.os.RemoteException; 29import android.os.ServiceManager; 30import android.util.Log; 31import android.util.Pair; 32 33import java.io.IOException; 34import java.util.Arrays; 35import java.util.Collections; 36import java.util.HashSet; 37import java.util.LinkedList; 38import java.util.Random; 39import java.util.Set; 40import java.util.UUID; 41 42/** 43 * Represents the local device Bluetooth adapter. The {@link BluetoothAdapter} 44 * lets you perform fundamental Bluetooth tasks, such as initiate 45 * device discovery, query a list of bonded (paired) devices, 46 * instantiate a {@link BluetoothDevice} using a known MAC address, and create 47 * a {@link BluetoothServerSocket} to listen for connection requests from other 48 * devices. 49 * 50 * <p>To get a {@link BluetoothAdapter} representing the local Bluetooth 51 * adapter, call the static {@link #getDefaultAdapter} method. 52 * Fundamentally, this is your starting point for all 53 * Bluetooth actions. Once you have the local adapter, you can get a set of 54 * {@link BluetoothDevice} objects representing all paired devices with 55 * {@link #getBondedDevices()}; start device discovery with 56 * {@link #startDiscovery()}; or create a {@link BluetoothServerSocket} to 57 * listen for incoming connection requests with 58 * {@link #listenUsingRfcommWithServiceRecord(String,UUID)}. 59 * 60 * <p class="note"><strong>Note:</strong> 61 * Most methods require the {@link android.Manifest.permission#BLUETOOTH} 62 * permission and some also require the 63 * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission. 64 * 65 * <div class="special reference"> 66 * <h3>Developer Guides</h3> 67 * <p>For more information about using Bluetooth, read the 68 * <a href="{@docRoot}guide/topics/wireless/bluetooth.html">Bluetooth</a> developer guide.</p> 69 * </div> 70 * 71 * {@see BluetoothDevice} 72 * {@see BluetoothServerSocket} 73 */ 74public final class BluetoothAdapter { 75 private static final String TAG = "BluetoothAdapter"; 76 private static final boolean DBG = true; 77 78 /** 79 * Sentinel error value for this class. Guaranteed to not equal any other 80 * integer constant in this class. Provided as a convenience for functions 81 * that require a sentinel error value, for example: 82 * <p><code>Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 83 * BluetoothAdapter.ERROR)</code> 84 */ 85 public static final int ERROR = Integer.MIN_VALUE; 86 87 /** 88 * Broadcast Action: The state of the local Bluetooth adapter has been 89 * changed. 90 * <p>For example, Bluetooth has been turned on or off. 91 * <p>Always contains the extra fields {@link #EXTRA_STATE} and {@link 92 * #EXTRA_PREVIOUS_STATE} containing the new and old states 93 * respectively. 94 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 95 */ 96 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 97 public static final String ACTION_STATE_CHANGED = 98 "android.bluetooth.adapter.action.STATE_CHANGED"; 99 100 /** 101 * Used as an int extra field in {@link #ACTION_STATE_CHANGED} 102 * intents to request the current power state. Possible values are: 103 * {@link #STATE_OFF}, 104 * {@link #STATE_TURNING_ON}, 105 * {@link #STATE_ON}, 106 * {@link #STATE_TURNING_OFF}, 107 */ 108 public static final String EXTRA_STATE = 109 "android.bluetooth.adapter.extra.STATE"; 110 /** 111 * Used as an int extra field in {@link #ACTION_STATE_CHANGED} 112 * intents to request the previous power state. Possible values are: 113 * {@link #STATE_OFF}, 114 * {@link #STATE_TURNING_ON}, 115 * {@link #STATE_ON}, 116 * {@link #STATE_TURNING_OFF}, 117 */ 118 public static final String EXTRA_PREVIOUS_STATE = 119 "android.bluetooth.adapter.extra.PREVIOUS_STATE"; 120 121 /** 122 * Indicates the local Bluetooth adapter is off. 123 */ 124 public static final int STATE_OFF = 10; 125 /** 126 * Indicates the local Bluetooth adapter is turning on. However local 127 * clients should wait for {@link #STATE_ON} before attempting to 128 * use the adapter. 129 */ 130 public static final int STATE_TURNING_ON = 11; 131 /** 132 * Indicates the local Bluetooth adapter is on, and ready for use. 133 */ 134 public static final int STATE_ON = 12; 135 /** 136 * Indicates the local Bluetooth adapter is turning off. Local clients 137 * should immediately attempt graceful disconnection of any remote links. 138 */ 139 public static final int STATE_TURNING_OFF = 13; 140 141 /** 142 * Activity Action: Show a system activity that requests discoverable mode. 143 * This activity will also request the user to turn on Bluetooth if it 144 * is not currently enabled. 145 * <p>Discoverable mode is equivalent to {@link 146 * #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. It allows remote devices to see 147 * this Bluetooth adapter when they perform a discovery. 148 * <p>For privacy, Android is not discoverable by default. 149 * <p>The sender of this Intent can optionally use extra field {@link 150 * #EXTRA_DISCOVERABLE_DURATION} to request the duration of 151 * discoverability. Currently the default duration is 120 seconds, and 152 * maximum duration is capped at 300 seconds for each request. 153 * <p>Notification of the result of this activity is posted using the 154 * {@link android.app.Activity#onActivityResult} callback. The 155 * <code>resultCode</code> 156 * will be the duration (in seconds) of discoverability or 157 * {@link android.app.Activity#RESULT_CANCELED} if the user rejected 158 * discoverability or an error has occurred. 159 * <p>Applications can also listen for {@link #ACTION_SCAN_MODE_CHANGED} 160 * for global notification whenever the scan mode changes. For example, an 161 * application can be notified when the device has ended discoverability. 162 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 163 */ 164 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 165 public static final String ACTION_REQUEST_DISCOVERABLE = 166 "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE"; 167 168 /** 169 * Used as an optional int extra field in {@link 170 * #ACTION_REQUEST_DISCOVERABLE} intents to request a specific duration 171 * for discoverability in seconds. The current default is 120 seconds, and 172 * requests over 300 seconds will be capped. These values could change. 173 */ 174 public static final String EXTRA_DISCOVERABLE_DURATION = 175 "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION"; 176 177 /** 178 * Activity Action: Show a system activity that allows the user to turn on 179 * Bluetooth. 180 * <p>This system activity will return once Bluetooth has completed turning 181 * on, or the user has decided not to turn Bluetooth on. 182 * <p>Notification of the result of this activity is posted using the 183 * {@link android.app.Activity#onActivityResult} callback. The 184 * <code>resultCode</code> 185 * will be {@link android.app.Activity#RESULT_OK} if Bluetooth has been 186 * turned on or {@link android.app.Activity#RESULT_CANCELED} if the user 187 * has rejected the request or an error has occurred. 188 * <p>Applications can also listen for {@link #ACTION_STATE_CHANGED} 189 * for global notification whenever Bluetooth is turned on or off. 190 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 191 */ 192 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 193 public static final String ACTION_REQUEST_ENABLE = 194 "android.bluetooth.adapter.action.REQUEST_ENABLE"; 195 196 /** 197 * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter 198 * has changed. 199 * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link 200 * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes 201 * respectively. 202 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 203 */ 204 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 205 public static final String ACTION_SCAN_MODE_CHANGED = 206 "android.bluetooth.adapter.action.SCAN_MODE_CHANGED"; 207 208 /** 209 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED} 210 * intents to request the current scan mode. Possible values are: 211 * {@link #SCAN_MODE_NONE}, 212 * {@link #SCAN_MODE_CONNECTABLE}, 213 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}, 214 */ 215 public static final String EXTRA_SCAN_MODE = "android.bluetooth.adapter.extra.SCAN_MODE"; 216 /** 217 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED} 218 * intents to request the previous scan mode. Possible values are: 219 * {@link #SCAN_MODE_NONE}, 220 * {@link #SCAN_MODE_CONNECTABLE}, 221 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}, 222 */ 223 public static final String EXTRA_PREVIOUS_SCAN_MODE = 224 "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE"; 225 226 /** 227 * Indicates that both inquiry scan and page scan are disabled on the local 228 * Bluetooth adapter. Therefore this device is neither discoverable 229 * nor connectable from remote Bluetooth devices. 230 */ 231 public static final int SCAN_MODE_NONE = 20; 232 /** 233 * Indicates that inquiry scan is disabled, but page scan is enabled on the 234 * local Bluetooth adapter. Therefore this device is not discoverable from 235 * remote Bluetooth devices, but is connectable from remote devices that 236 * have previously discovered this device. 237 */ 238 public static final int SCAN_MODE_CONNECTABLE = 21; 239 /** 240 * Indicates that both inquiry scan and page scan are enabled on the local 241 * Bluetooth adapter. Therefore this device is both discoverable and 242 * connectable from remote Bluetooth devices. 243 */ 244 public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23; 245 246 247 /** 248 * Broadcast Action: The local Bluetooth adapter has started the remote 249 * device discovery process. 250 * <p>This usually involves an inquiry scan of about 12 seconds, followed 251 * by a page scan of each new device to retrieve its Bluetooth name. 252 * <p>Register for {@link BluetoothDevice#ACTION_FOUND} to be notified as 253 * remote Bluetooth devices are found. 254 * <p>Device discovery is a heavyweight procedure. New connections to 255 * remote Bluetooth devices should not be attempted while discovery is in 256 * progress, and existing connections will experience limited bandwidth 257 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 258 * discovery. 259 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 260 */ 261 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 262 public static final String ACTION_DISCOVERY_STARTED = 263 "android.bluetooth.adapter.action.DISCOVERY_STARTED"; 264 /** 265 * Broadcast Action: The local Bluetooth adapter has finished the device 266 * discovery process. 267 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 268 */ 269 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 270 public static final String ACTION_DISCOVERY_FINISHED = 271 "android.bluetooth.adapter.action.DISCOVERY_FINISHED"; 272 273 /** 274 * Broadcast Action: The local Bluetooth adapter has changed its friendly 275 * Bluetooth name. 276 * <p>This name is visible to remote Bluetooth devices. 277 * <p>Always contains the extra field {@link #EXTRA_LOCAL_NAME} containing 278 * the name. 279 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 280 */ 281 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 282 public static final String ACTION_LOCAL_NAME_CHANGED = 283 "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED"; 284 /** 285 * Used as a String extra field in {@link #ACTION_LOCAL_NAME_CHANGED} 286 * intents to request the local Bluetooth name. 287 */ 288 public static final String EXTRA_LOCAL_NAME = "android.bluetooth.adapter.extra.LOCAL_NAME"; 289 290 /** 291 * Intent used to broadcast the change in connection state of the local 292 * Bluetooth adapter to a profile of the remote device. When the adapter is 293 * not connected to any profiles of any remote devices and it attempts a 294 * connection to a profile this intent will sent. Once connected, this intent 295 * will not be sent for any more connection attempts to any profiles of any 296 * remote device. When the adapter disconnects from the last profile its 297 * connected to of any remote device, this intent will be sent. 298 * 299 * <p> This intent is useful for applications that are only concerned about 300 * whether the local adapter is connected to any profile of any device and 301 * are not really concerned about which profile. For example, an application 302 * which displays an icon to display whether Bluetooth is connected or not 303 * can use this intent. 304 * 305 * <p>This intent will have 3 extras: 306 * {@link #EXTRA_CONNECTION_STATE} - The current connection state. 307 * {@link #EXTRA_PREVIOUS_CONNECTION_STATE}- The previous connection state. 308 * {@link BluetoothDevice#EXTRA_DEVICE} - The remote device. 309 * 310 * {@link #EXTRA_CONNECTION_STATE} or {@link #EXTRA_PREVIOUS_CONNECTION_STATE} 311 * can be any of {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING}, 312 * {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}. 313 * 314 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 315 */ 316 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 317 public static final String ACTION_CONNECTION_STATE_CHANGED = 318 "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED"; 319 320 /** 321 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED} 322 * 323 * This extra represents the current connection state. 324 */ 325 public static final String EXTRA_CONNECTION_STATE = 326 "android.bluetooth.adapter.extra.CONNECTION_STATE"; 327 328 /** 329 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED} 330 * 331 * This extra represents the previous connection state. 332 */ 333 public static final String EXTRA_PREVIOUS_CONNECTION_STATE = 334 "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE"; 335 336 /** The profile is in disconnected state */ 337 public static final int STATE_DISCONNECTED = 0; 338 /** The profile is in connecting state */ 339 public static final int STATE_CONNECTING = 1; 340 /** The profile is in connected state */ 341 public static final int STATE_CONNECTED = 2; 342 /** The profile is in disconnecting state */ 343 public static final int STATE_DISCONNECTING = 3; 344 345 /** @hide */ 346 public static final String BLUETOOTH_MANAGER_SERVICE = "bluetooth_manager"; 347 348 private static final int ADDRESS_LENGTH = 17; 349 350 /** 351 * Lazily initialized singleton. Guaranteed final after first object 352 * constructed. 353 */ 354 private static BluetoothAdapter sAdapter; 355 356 private final IBluetoothManager mManagerService; 357 private IBluetooth mService; 358 359 private Handler mServiceRecordHandler; 360 361 /** 362 * Get a handle to the default local Bluetooth adapter. 363 * <p>Currently Android only supports one Bluetooth adapter, but the API 364 * could be extended to support more. This will always return the default 365 * adapter. 366 * @return the default local adapter, or null if Bluetooth is not supported 367 * on this hardware platform 368 */ 369 public static synchronized BluetoothAdapter getDefaultAdapter() { 370 if (sAdapter == null) { 371 IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE); 372 if (b != null) { 373 IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b); 374 sAdapter = new BluetoothAdapter(managerService); 375 } else { 376 Log.e(TAG, "Bluetooth binder is null"); 377 } 378 } 379 return sAdapter; 380 } 381 382 /** 383 * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance. 384 */ 385 BluetoothAdapter(IBluetoothManager managerService) { 386 387 if (managerService == null) { 388 throw new IllegalArgumentException("bluetooth manager service is null"); 389 } 390 try { 391 mService = managerService.registerAdapter(mManagerCallback); 392 } catch (RemoteException e) {Log.e(TAG, "", e);} 393 mManagerService = managerService; 394 mServiceRecordHandler = null; 395 } 396 397 /** 398 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware 399 * address. 400 * <p>Valid Bluetooth hardware addresses must be upper case, in a format 401 * such as "00:11:22:33:AA:BB". The helper {@link #checkBluetoothAddress} is 402 * available to validate a Bluetooth address. 403 * <p>A {@link BluetoothDevice} will always be returned for a valid 404 * hardware address, even if this adapter has never seen that device. 405 * 406 * @param address valid Bluetooth MAC address 407 * @throws IllegalArgumentException if address is invalid 408 */ 409 public BluetoothDevice getRemoteDevice(String address) { 410 if (mService == null) { 411 Log.e(TAG, "BT not enabled. Cannot create Remote Device"); 412 return null; 413 } 414 return new BluetoothDevice(address); 415 } 416 417 /** 418 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware 419 * address. 420 * <p>Valid Bluetooth hardware addresses must be 6 bytes. This method 421 * expects the address in network byte order (MSB first). 422 * <p>A {@link BluetoothDevice} will always be returned for a valid 423 * hardware address, even if this adapter has never seen that device. 424 * 425 * @param address Bluetooth MAC address (6 bytes) 426 * @throws IllegalArgumentException if address is invalid 427 */ 428 public BluetoothDevice getRemoteDevice(byte[] address) { 429 if (address == null || address.length != 6) { 430 throw new IllegalArgumentException("Bluetooth address must have 6 bytes"); 431 } 432 return new BluetoothDevice(String.format("%02X:%02X:%02X:%02X:%02X:%02X", 433 address[0], address[1], address[2], address[3], address[4], address[5])); 434 } 435 436 /** 437 * Return true if Bluetooth is currently enabled and ready for use. 438 * <p>Equivalent to: 439 * <code>getBluetoothState() == STATE_ON</code> 440 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 441 * 442 * @return true if the local adapter is turned on 443 */ 444 public boolean isEnabled() { 445 446 try { 447 synchronized(mManagerCallback) { 448 if (mService != null) return mService.isEnabled(); 449 } 450 } catch (RemoteException e) {Log.e(TAG, "", e);} 451 return false; 452 } 453 454 /** 455 * Get the current state of the local Bluetooth adapter. 456 * <p>Possible return values are 457 * {@link #STATE_OFF}, 458 * {@link #STATE_TURNING_ON}, 459 * {@link #STATE_ON}, 460 * {@link #STATE_TURNING_OFF}. 461 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 462 * 463 * @return current state of Bluetooth adapter 464 */ 465 public int getState() { 466 try { 467 synchronized(mManagerCallback) { 468 if (mService != null) 469 { 470 return mService.getState(); 471 } 472 // TODO(BT) there might be a small gap during STATE_TURNING_ON that 473 // mService is null, handle that case 474 } 475 } catch (RemoteException e) {Log.e(TAG, "", e);} 476 return STATE_OFF; 477 } 478 479 /** 480 * Turn on the local Bluetooth adapter—do not use without explicit 481 * user action to turn on Bluetooth. 482 * <p>This powers on the underlying Bluetooth hardware, and starts all 483 * Bluetooth system services. 484 * <p class="caution"><strong>Bluetooth should never be enabled without 485 * direct user consent</strong>. If you want to turn on Bluetooth in order 486 * to create a wireless connection, you should use the {@link 487 * #ACTION_REQUEST_ENABLE} Intent, which will raise a dialog that requests 488 * user permission to turn on Bluetooth. The {@link #enable()} method is 489 * provided only for applications that include a user interface for changing 490 * system settings, such as a "power manager" app.</p> 491 * <p>This is an asynchronous call: it will return immediately, and 492 * clients should listen for {@link #ACTION_STATE_CHANGED} 493 * to be notified of subsequent adapter state changes. If this call returns 494 * true, then the adapter state will immediately transition from {@link 495 * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time 496 * later transition to either {@link #STATE_OFF} or {@link 497 * #STATE_ON}. If this call returns false then there was an 498 * immediate problem that will prevent the adapter from being turned on - 499 * such as Airplane mode, or the adapter is already turned on. 500 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 501 * permission 502 * 503 * @return true to indicate adapter startup has begun, or false on 504 * immediate error 505 */ 506 public boolean enable() { 507 508 boolean enabled = false; 509 try { 510 enabled = mManagerService.enable(); 511 if (enabled) { 512 // TODO(BT) 513 } 514 } catch (RemoteException e) {Log.e(TAG, "", e);} 515 return false; 516 } 517 518 /** 519 * Turn off the local Bluetooth adapter—do not use without explicit 520 * user action to turn off Bluetooth. 521 * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth 522 * system services, and powers down the underlying Bluetooth hardware. 523 * <p class="caution"><strong>Bluetooth should never be disabled without 524 * direct user consent</strong>. The {@link #disable()} method is 525 * provided only for applications that include a user interface for changing 526 * system settings, such as a "power manager" app.</p> 527 * <p>This is an asynchronous call: it will return immediately, and 528 * clients should listen for {@link #ACTION_STATE_CHANGED} 529 * to be notified of subsequent adapter state changes. If this call returns 530 * true, then the adapter state will immediately transition from {@link 531 * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time 532 * later transition to either {@link #STATE_OFF} or {@link 533 * #STATE_ON}. If this call returns false then there was an 534 * immediate problem that will prevent the adapter from being turned off - 535 * such as the adapter already being turned off. 536 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 537 * permission 538 * 539 * @return true to indicate adapter shutdown has begun, or false on 540 * immediate error 541 */ 542 public boolean disable() { 543 try { 544 return mManagerService.disable(true); 545 } catch (RemoteException e) {Log.e(TAG, "", e);} 546 return false; 547 } 548 549 /** 550 * Turn off the local Bluetooth adapter and don't persist the setting. 551 * 552 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 553 * permission 554 * 555 * @return true to indicate adapter shutdown has begun, or false on 556 * immediate error 557 * @hide 558 */ 559 public boolean disable(boolean persist) { 560 561 try { 562 return mManagerService.disable(persist); 563 } catch (RemoteException e) {Log.e(TAG, "", e);} 564 return false; 565 } 566 567 /** 568 * Returns the hardware address of the local Bluetooth adapter. 569 * <p>For example, "00:11:22:AA:BB:CC". 570 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 571 * 572 * @return Bluetooth hardware address as string 573 */ 574 public String getAddress() { 575 try { 576 return mManagerService.getAddress(); 577 } catch (RemoteException e) {Log.e(TAG, "", e);} 578 return null; 579 } 580 581 /** 582 * Get the friendly Bluetooth name of the local Bluetooth adapter. 583 * <p>This name is visible to remote Bluetooth devices. 584 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 585 * 586 * @return the Bluetooth name, or null on error 587 */ 588 public String getName() { 589 try { 590 return mManagerService.getName(); 591 } catch (RemoteException e) {Log.e(TAG, "", e);} 592 return null; 593 } 594 595 /** 596 * Get the UUIDs supported by the local Bluetooth adapter. 597 * 598 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 599 * 600 * @return the UUIDs supported by the local Bluetooth Adapter. 601 * @hide 602 */ 603 public ParcelUuid[] getUuids() { 604 if (getState() != STATE_ON) return null; 605 try { 606 synchronized(mManagerCallback) { 607 if (mService != null) return mService.getUuids(); 608 } 609 } catch (RemoteException e) {Log.e(TAG, "", e);} 610 return null; 611 } 612 613 /** 614 * Set the friendly Bluetooth name of the local Bluetooth adapter. 615 * <p>This name is visible to remote Bluetooth devices. 616 * <p>Valid Bluetooth names are a maximum of 248 bytes using UTF-8 617 * encoding, although many remote devices can only display the first 618 * 40 characters, and some may be limited to just 20. 619 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 620 * will return false. After turning on Bluetooth, 621 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 622 * to get the updated value. 623 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} 624 * 625 * @param name a valid Bluetooth name 626 * @return true if the name was set, false otherwise 627 */ 628 public boolean setName(String name) { 629 if (getState() != STATE_ON) return false; 630 try { 631 synchronized(mManagerCallback) { 632 if (mService != null) return mService.setName(name); 633 } 634 } catch (RemoteException e) {Log.e(TAG, "", e);} 635 return false; 636 } 637 638 /** 639 * Get the current Bluetooth scan mode of the local Bluetooth adapter. 640 * <p>The Bluetooth scan mode determines if the local adapter is 641 * connectable and/or discoverable from remote Bluetooth devices. 642 * <p>Possible values are: 643 * {@link #SCAN_MODE_NONE}, 644 * {@link #SCAN_MODE_CONNECTABLE}, 645 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. 646 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 647 * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth, 648 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 649 * to get the updated value. 650 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 651 * 652 * @return scan mode 653 */ 654 public int getScanMode() { 655 if (getState() != STATE_ON) return SCAN_MODE_NONE; 656 try { 657 synchronized(mManagerCallback) { 658 if (mService != null) return mService.getScanMode(); 659 } 660 } catch (RemoteException e) {Log.e(TAG, "", e);} 661 return SCAN_MODE_NONE; 662 } 663 664 /** 665 * Set the 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>For privacy reasons, discoverable mode is automatically turned off 669 * after <code>duration</code> seconds. For example, 120 seconds should be 670 * enough for a remote device to initiate and complete its discovery 671 * process. 672 * <p>Valid scan mode values are: 673 * {@link #SCAN_MODE_NONE}, 674 * {@link #SCAN_MODE_CONNECTABLE}, 675 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. 676 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 677 * will return false. After turning on Bluetooth, 678 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 679 * to get the updated value. 680 * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} 681 * <p>Applications cannot set the scan mode. They should use 682 * <code>startActivityForResult( 683 * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE}) 684 * </code>instead. 685 * 686 * @param mode valid scan mode 687 * @param duration time in seconds to apply scan mode, only used for 688 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE} 689 * @return true if the scan mode was set, false otherwise 690 * @hide 691 */ 692 public boolean setScanMode(int mode, int duration) { 693 if (getState() != STATE_ON) return false; 694 try { 695 synchronized(mManagerCallback) { 696 if (mService != null) return mService.setScanMode(mode, duration); 697 } 698 } catch (RemoteException e) {Log.e(TAG, "", e);} 699 return false; 700 } 701 702 /** @hide */ 703 public boolean setScanMode(int mode) { 704 if (getState() != STATE_ON) return false; 705 /* getDiscoverableTimeout() to use the latest from NV than use 0 */ 706 return setScanMode(mode, getDiscoverableTimeout()); 707 } 708 709 /** @hide */ 710 public int getDiscoverableTimeout() { 711 if (getState() != STATE_ON) return -1; 712 try { 713 synchronized(mManagerCallback) { 714 if (mService != null) return mService.getDiscoverableTimeout(); 715 } 716 } catch (RemoteException e) {Log.e(TAG, "", e);} 717 return -1; 718 } 719 720 /** @hide */ 721 public void setDiscoverableTimeout(int timeout) { 722 if (getState() != STATE_ON) return; 723 try { 724 synchronized(mManagerCallback) { 725 if (mService != null) mService.setDiscoverableTimeout(timeout); 726 } 727 } catch (RemoteException e) {Log.e(TAG, "", e);} 728 } 729 730 /** 731 * Start the remote device discovery process. 732 * <p>The discovery process usually involves an inquiry scan of about 12 733 * seconds, followed by a page scan of each new device to retrieve its 734 * Bluetooth name. 735 * <p>This is an asynchronous call, it will return immediately. Register 736 * for {@link #ACTION_DISCOVERY_STARTED} and {@link 737 * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the 738 * discovery starts and completes. Register for {@link 739 * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices 740 * are found. 741 * <p>Device discovery is a heavyweight procedure. New connections to 742 * remote Bluetooth devices should not be attempted while discovery is in 743 * progress, and existing connections will experience limited bandwidth 744 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 745 * discovery. Discovery is not managed by the Activity, 746 * but is run as a system service, so an application should always call 747 * {@link BluetoothAdapter#cancelDiscovery()} even if it 748 * did not directly request a discovery, just to be sure. 749 * <p>Device discovery will only find remote devices that are currently 750 * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are 751 * not discoverable by default, and need to be entered into a special mode. 752 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 753 * will return false. After turning on Bluetooth, 754 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 755 * to get the updated value. 756 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}. 757 * 758 * @return true on success, false on error 759 */ 760 public boolean startDiscovery() { 761 if (getState() != STATE_ON) return false; 762 try { 763 synchronized(mManagerCallback) { 764 if (mService != null) return mService.startDiscovery(); 765 } 766 } catch (RemoteException e) {Log.e(TAG, "", e);} 767 return false; 768 } 769 770 /** 771 * Cancel the current device discovery process. 772 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}. 773 * <p>Because discovery is a heavyweight procedure for the Bluetooth 774 * adapter, this method should always be called before attempting to connect 775 * to a remote device with {@link 776 * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by 777 * the Activity, but is run as a system service, so an application should 778 * always call cancel discovery even if it did not directly request a 779 * discovery, just to be sure. 780 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 781 * will return false. After turning on Bluetooth, 782 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 783 * to get the updated value. 784 * 785 * @return true on success, false on error 786 */ 787 public boolean cancelDiscovery() { 788 if (getState() != STATE_ON) return false; 789 try { 790 synchronized(mManagerCallback) { 791 if (mService != null) return mService.cancelDiscovery(); 792 } 793 } catch (RemoteException e) {Log.e(TAG, "", e);} 794 return false; 795 } 796 797 /** 798 * Return true if the local Bluetooth adapter is currently in the device 799 * discovery process. 800 * <p>Device discovery is a heavyweight procedure. New connections to 801 * remote Bluetooth devices should not be attempted while discovery is in 802 * progress, and existing connections will experience limited bandwidth 803 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 804 * discovery. 805 * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED} 806 * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery 807 * starts or completes. 808 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 809 * will return false. After turning on Bluetooth, 810 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 811 * to get the updated value. 812 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 813 * 814 * @return true if discovering 815 */ 816 public boolean isDiscovering() { 817 if (getState() != STATE_ON) return false; 818 try { 819 synchronized(mManagerCallback) { 820 if (mService != null ) return mService.isDiscovering(); 821 } 822 } catch (RemoteException e) {Log.e(TAG, "", e);} 823 return false; 824 } 825 826 /** 827 * Return the set of {@link BluetoothDevice} objects that are bonded 828 * (paired) to the local adapter. 829 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 830 * will return an empty set. After turning on Bluetooth, 831 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 832 * to get the updated value. 833 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 834 * 835 * @return unmodifiable set of {@link BluetoothDevice}, or null on error 836 */ 837 public Set<BluetoothDevice> getBondedDevices() { 838 if (getState() != STATE_ON) { 839 return toDeviceSet(new BluetoothDevice[0]); 840 } 841 try { 842 synchronized(mManagerCallback) { 843 if (mService != null) return toDeviceSet(mService.getBondedDevices()); 844 } 845 return toDeviceSet(new BluetoothDevice[0]); 846 } catch (RemoteException e) {Log.e(TAG, "", e);} 847 return null; 848 } 849 850 /** 851 * Get the current connection state of the local Bluetooth adapter. 852 * This can be used to check whether the local Bluetooth adapter is connected 853 * to any profile of any other remote Bluetooth Device. 854 * 855 * <p> Use this function along with {@link #ACTION_CONNECTION_STATE_CHANGED} 856 * intent to get the connection state of the adapter. 857 * 858 * @return One of {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTED}, 859 * {@link #STATE_CONNECTING} or {@link #STATE_DISCONNECTED} 860 * 861 * @hide 862 */ 863 public int getConnectionState() { 864 if (getState() != STATE_ON) return BluetoothAdapter.STATE_DISCONNECTED; 865 try { 866 synchronized(mManagerCallback) { 867 if (mService != null) return mService.getAdapterConnectionState(); 868 } 869 } catch (RemoteException e) {Log.e(TAG, "getConnectionState:", e);} 870 return BluetoothAdapter.STATE_DISCONNECTED; 871 } 872 873 /** 874 * Get the current connection state of a profile. 875 * This function can be used to check whether the local Bluetooth adapter 876 * is connected to any remote device for a specific profile. 877 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET}, 878 * {@link BluetoothProfile#A2DP}. 879 * 880 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 881 * 882 * <p> Return value can be one of 883 * {@link BluetoothProfile#STATE_DISCONNECTED}, 884 * {@link BluetoothProfile#STATE_CONNECTING}, 885 * {@link BluetoothProfile#STATE_CONNECTED}, 886 * {@link BluetoothProfile#STATE_DISCONNECTING} 887 */ 888 public int getProfileConnectionState(int profile) { 889 if (getState() != STATE_ON) return BluetoothProfile.STATE_DISCONNECTED; 890 try { 891 synchronized(mManagerCallback) { 892 if (mService != null) return mService.getProfileConnectionState(profile); 893 } 894 } catch (RemoteException e) { 895 Log.e(TAG, "getProfileConnectionState:", e); 896 } 897 return BluetoothProfile.STATE_DISCONNECTED; 898 } 899 900 /** 901 * Create a listening, secure RFCOMM Bluetooth socket. 902 * <p>A remote device connecting to this socket will be authenticated and 903 * communication on this socket will be encrypted. 904 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 905 * connections from a listening {@link BluetoothServerSocket}. 906 * <p>Valid RFCOMM channels are in range 1 to 30. 907 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} 908 * @param channel RFCOMM channel to listen on 909 * @return a listening RFCOMM BluetoothServerSocket 910 * @throws IOException on error, for example Bluetooth not available, or 911 * insufficient permissions, or channel in use. 912 * @hide 913 */ 914 public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException { 915 BluetoothServerSocket socket = new BluetoothServerSocket( 916 BluetoothSocket.TYPE_RFCOMM, true, true, channel); 917 int errno = socket.mSocket.bindListen(); 918 if (errno != 0) { 919 //TODO(BT): Throw the same exception error code 920 // that the previous code was using. 921 //socket.mSocket.throwErrnoNative(errno); 922 throw new IOException("Error: " + errno); 923 } 924 return socket; 925 } 926 927 /** 928 * Create a listening, secure RFCOMM Bluetooth socket with Service Record. 929 * <p>A remote device connecting to this socket will be authenticated and 930 * communication on this socket will be encrypted. 931 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 932 * connections from a listening {@link BluetoothServerSocket}. 933 * <p>The system will assign an unused RFCOMM channel to listen on. 934 * <p>The system will also register a Service Discovery 935 * Protocol (SDP) record with the local SDP server containing the specified 936 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 937 * can use the same UUID to query our SDP server and discover which channel 938 * to connect to. This SDP record will be removed when this socket is 939 * closed, or if this application closes unexpectedly. 940 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 941 * connect to this socket from another device using the same {@link UUID}. 942 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 943 * @param name service name for SDP record 944 * @param uuid uuid for SDP record 945 * @return a listening RFCOMM BluetoothServerSocket 946 * @throws IOException on error, for example Bluetooth not available, or 947 * insufficient permissions, or channel in use. 948 */ 949 public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid) 950 throws IOException { 951 return createNewRfcommSocketAndRecord(name, uuid, true, true); 952 } 953 954 /** 955 * Create a listening, insecure RFCOMM Bluetooth socket with Service Record. 956 * <p>The link key is not required to be authenticated, i.e the communication may be 957 * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices, 958 * the link will be encrypted, as encryption is mandartory. 959 * For legacy devices (pre Bluetooth 2.1 devices) the link will not 960 * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an 961 * encrypted and authenticated communication channel is desired. 962 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 963 * connections from a listening {@link BluetoothServerSocket}. 964 * <p>The system will assign an unused RFCOMM channel to listen on. 965 * <p>The system will also register a Service Discovery 966 * Protocol (SDP) record with the local SDP server containing the specified 967 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 968 * can use the same UUID to query our SDP server and discover which channel 969 * to connect to. This SDP record will be removed when this socket is 970 * closed, or if this application closes unexpectedly. 971 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 972 * connect to this socket from another device using the same {@link UUID}. 973 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 974 * @param name service name for SDP record 975 * @param uuid uuid for SDP record 976 * @return a listening RFCOMM BluetoothServerSocket 977 * @throws IOException on error, for example Bluetooth not available, or 978 * insufficient permissions, or channel in use. 979 */ 980 public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid) 981 throws IOException { 982 return createNewRfcommSocketAndRecord(name, uuid, false, false); 983 } 984 985 /** 986 * Create a listening, encrypted, 987 * RFCOMM Bluetooth socket with Service Record. 988 * <p>The link will be encrypted, but the link key is not required to be authenticated 989 * i.e the communication is vulnerable to Man In the Middle attacks. Use 990 * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key. 991 * <p> Use this socket if authentication of link key is not possible. 992 * For example, for Bluetooth 2.1 devices, if any of the devices does not have 993 * an input and output capability or just has the ability to display a numeric key, 994 * a secure socket connection is not possible and this socket can be used. 995 * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required. 996 * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory. 997 * For more details, refer to the Security Model section 5.2 (vol 3) of 998 * Bluetooth Core Specification version 2.1 + EDR. 999 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 1000 * connections from a listening {@link BluetoothServerSocket}. 1001 * <p>The system will assign an unused RFCOMM channel to listen on. 1002 * <p>The system will also register a Service Discovery 1003 * Protocol (SDP) record with the local SDP server containing the specified 1004 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 1005 * can use the same UUID to query our SDP server and discover which channel 1006 * to connect to. This SDP record will be removed when this socket is 1007 * closed, or if this application closes unexpectedly. 1008 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 1009 * connect to this socket from another device using the same {@link UUID}. 1010 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1011 * @param name service name for SDP record 1012 * @param uuid uuid for SDP record 1013 * @return a listening RFCOMM BluetoothServerSocket 1014 * @throws IOException on error, for example Bluetooth not available, or 1015 * insufficient permissions, or channel in use. 1016 * @hide 1017 */ 1018 public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord( 1019 String name, UUID uuid) throws IOException { 1020 return createNewRfcommSocketAndRecord(name, uuid, false, true); 1021 } 1022 1023 1024 private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid, 1025 boolean auth, boolean encrypt) throws IOException { 1026 BluetoothServerSocket socket; 1027 socket = new BluetoothServerSocket(BluetoothSocket.TYPE_RFCOMM, auth, 1028 encrypt, new ParcelUuid(uuid)); 1029 socket.setServiceName(name); 1030 int errno = socket.mSocket.bindListen(); 1031 if (errno != 0) { 1032 //TODO(BT): Throw the same exception error code 1033 // that the previous code was using. 1034 //socket.mSocket.throwErrnoNative(errno); 1035 throw new IOException("Error: " + errno); 1036 } 1037 return socket; 1038 } 1039 1040 /** 1041 * Construct an unencrypted, unauthenticated, RFCOMM server socket. 1042 * Call #accept to retrieve connections to this socket. 1043 * @return An RFCOMM BluetoothServerSocket 1044 * @throws IOException On error, for example Bluetooth not available, or 1045 * insufficient permissions. 1046 * @hide 1047 */ 1048 public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException { 1049 BluetoothServerSocket socket = new BluetoothServerSocket( 1050 BluetoothSocket.TYPE_RFCOMM, false, false, port); 1051 int errno = socket.mSocket.bindListen(); 1052 if (errno != 0) { 1053 //TODO(BT): Throw the same exception error code 1054 // that the previous code was using. 1055 //socket.mSocket.throwErrnoNative(errno); 1056 throw new IOException("Error: " + errno); 1057 } 1058 return socket; 1059 } 1060 1061 /** 1062 * Construct an encrypted, RFCOMM server socket. 1063 * Call #accept to retrieve connections to this socket. 1064 * @return An RFCOMM BluetoothServerSocket 1065 * @throws IOException On error, for example Bluetooth not available, or 1066 * insufficient permissions. 1067 * @hide 1068 */ 1069 public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port) 1070 throws IOException { 1071 BluetoothServerSocket socket = new BluetoothServerSocket( 1072 BluetoothSocket.TYPE_RFCOMM, false, true, port); 1073 int errno = socket.mSocket.bindListen(); 1074 if (errno < 0) { 1075 //TODO(BT): Throw the same exception error code 1076 // that the previous code was using. 1077 //socket.mSocket.throwErrnoNative(errno); 1078 throw new IOException("Error: " + errno); 1079 } 1080 return socket; 1081 } 1082 1083 /** 1084 * Construct a SCO server socket. 1085 * Call #accept to retrieve connections to this socket. 1086 * @return A SCO BluetoothServerSocket 1087 * @throws IOException On error, for example Bluetooth not available, or 1088 * insufficient permissions. 1089 * @hide 1090 */ 1091 public static BluetoothServerSocket listenUsingScoOn() throws IOException { 1092 BluetoothServerSocket socket = new BluetoothServerSocket( 1093 BluetoothSocket.TYPE_SCO, false, false, -1); 1094 int errno = socket.mSocket.bindListen(); 1095 if (errno < 0) { 1096 //TODO(BT): Throw the same exception error code 1097 // that the previous code was using. 1098 //socket.mSocket.throwErrnoNative(errno); 1099 } 1100 return socket; 1101 } 1102 1103 /** 1104 * Read the local Out of Band Pairing Data 1105 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1106 * 1107 * @return Pair<byte[], byte[]> of Hash and Randomizer 1108 * 1109 * @hide 1110 */ 1111 public Pair<byte[], byte[]> readOutOfBandData() { 1112 if (getState() != STATE_ON) return null; 1113 //TODO(BT 1114 /* 1115 try { 1116 byte[] hash; 1117 byte[] randomizer; 1118 1119 byte[] ret = mService.readOutOfBandData(); 1120 1121 if (ret == null || ret.length != 32) return null; 1122 1123 hash = Arrays.copyOfRange(ret, 0, 16); 1124 randomizer = Arrays.copyOfRange(ret, 16, 32); 1125 1126 if (DBG) { 1127 Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) + 1128 ":" + Arrays.toString(randomizer)); 1129 } 1130 return new Pair<byte[], byte[]>(hash, randomizer); 1131 1132 } catch (RemoteException e) {Log.e(TAG, "", e);}*/ 1133 return null; 1134 } 1135 1136 /** 1137 * Get the profile proxy object associated with the profile. 1138 * 1139 * <p>Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or 1140 * {@link BluetoothProfile#A2DP}. Clients must implements 1141 * {@link BluetoothProfile.ServiceListener} to get notified of 1142 * the connection status and to get the proxy object. 1143 * 1144 * @param context Context of the application 1145 * @param listener The service Listener for connection callbacks. 1146 * @param profile The Bluetooth profile; either {@link BluetoothProfile#HEALTH}, 1147 * {@link BluetoothProfile#HEADSET} or {@link BluetoothProfile#A2DP}. 1148 * @return true on success, false on error 1149 */ 1150 public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener, 1151 int profile) { 1152 if (context == null || listener == null) return false; 1153 1154 if (profile == BluetoothProfile.HEADSET) { 1155 BluetoothHeadset headset = new BluetoothHeadset(context, listener); 1156 return true; 1157 } else if (profile == BluetoothProfile.A2DP) { 1158 BluetoothA2dp a2dp = new BluetoothA2dp(context, listener); 1159 return true; 1160 } else if (profile == BluetoothProfile.INPUT_DEVICE) { 1161 BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener); 1162 return true; 1163 } else if (profile == BluetoothProfile.PAN) { 1164 BluetoothPan pan = new BluetoothPan(context, listener); 1165 return true; 1166 } else if (profile == BluetoothProfile.HEALTH) { 1167 BluetoothHealth health = new BluetoothHealth(context, listener); 1168 return true; 1169 } else { 1170 return false; 1171 } 1172 } 1173 1174 /** 1175 * Close the connection of the profile proxy to the Service. 1176 * 1177 * <p> Clients should call this when they are no longer using 1178 * the proxy obtained from {@link #getProfileProxy}. 1179 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or 1180 * {@link BluetoothProfile#A2DP} 1181 * 1182 * @param profile 1183 * @param proxy Profile proxy object 1184 */ 1185 public void closeProfileProxy(int profile, BluetoothProfile proxy) { 1186 if (proxy == null) return; 1187 1188 switch (profile) { 1189 case BluetoothProfile.HEADSET: 1190 BluetoothHeadset headset = (BluetoothHeadset)proxy; 1191 headset.close(); 1192 break; 1193 case BluetoothProfile.A2DP: 1194 BluetoothA2dp a2dp = (BluetoothA2dp)proxy; 1195 a2dp.close(); 1196 break; 1197 case BluetoothProfile.INPUT_DEVICE: 1198 BluetoothInputDevice iDev = (BluetoothInputDevice)proxy; 1199 iDev.close(); 1200 break; 1201 case BluetoothProfile.PAN: 1202 BluetoothPan pan = (BluetoothPan)proxy; 1203 pan.close(); 1204 break; 1205 case BluetoothProfile.HEALTH: 1206 BluetoothHealth health = (BluetoothHealth)proxy; 1207 health.close(); 1208 break; 1209 } 1210 } 1211 1212 final private IBluetoothManagerCallback mManagerCallback = 1213 new IBluetoothManagerCallback.Stub() { 1214 public void onBluetoothServiceUp(IBluetooth bluetoothService) { 1215 if (DBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService); 1216 synchronized (mManagerCallback) { 1217 mService = bluetoothService; 1218 } 1219 } 1220 1221 public void onBluetoothServiceDown() { 1222 if (DBG) Log.d(TAG, "onBluetoothServiceDown: " + mService); 1223 synchronized (mManagerCallback) { 1224 mService = null; 1225 } 1226 } 1227 }; 1228 1229 /** 1230 * Enable the Bluetooth Adapter, but don't auto-connect devices 1231 * and don't persist state. Only for use by system applications. 1232 * @hide 1233 */ 1234 public boolean enableNoAutoConnect() { 1235 try { 1236 return mService.enableNoAutoConnect(); 1237 } catch (RemoteException e) {Log.e(TAG, "", e);} 1238 return false; 1239 } 1240 1241 /** 1242 * Enable control of the Bluetooth Adapter for a single application. 1243 * 1244 * <p>Some applications need to use Bluetooth for short periods of time to 1245 * transfer data but don't want all the associated implications like 1246 * automatic connection to headsets etc. 1247 * 1248 * <p> Multiple applications can call this. This is reference counted and 1249 * Bluetooth disabled only when no one else is using it. There will be no UI 1250 * shown to the user while bluetooth is being enabled. Any user action will 1251 * override this call. For example, if user wants Bluetooth on and the last 1252 * user of this API wanted to disable Bluetooth, Bluetooth will not be 1253 * turned off. 1254 * 1255 * <p> This API is only meant to be used by internal applications. Third 1256 * party applications but use {@link #enable} and {@link #disable} APIs. 1257 * 1258 * <p> If this API returns true, it means the callback will be called. 1259 * The callback will be called with the current state of Bluetooth. 1260 * If the state is not what was requested, an internal error would be the 1261 * reason. If Bluetooth is already on and if this function is called to turn 1262 * it on, the api will return true and a callback will be called. 1263 * 1264 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1265 * 1266 * @param on True for on, false for off. 1267 * @param callback The callback to notify changes to the state. 1268 * @hide 1269 */ 1270 public boolean changeApplicationBluetoothState(boolean on, 1271 BluetoothStateChangeCallback callback) { 1272 if (callback == null) return false; 1273 1274 //TODO(BT) 1275 /* 1276 try { 1277 return mService.changeApplicationBluetoothState(on, new 1278 StateChangeCallbackWrapper(callback), new Binder()); 1279 } catch (RemoteException e) { 1280 Log.e(TAG, "changeBluetoothState", e); 1281 }*/ 1282 return false; 1283 } 1284 1285 /** 1286 * @hide 1287 */ 1288 public interface BluetoothStateChangeCallback { 1289 public void onBluetoothStateChange(boolean on); 1290 } 1291 1292 /** 1293 * @hide 1294 */ 1295 public class StateChangeCallbackWrapper extends IBluetoothStateChangeCallback.Stub { 1296 private BluetoothStateChangeCallback mCallback; 1297 1298 StateChangeCallbackWrapper(BluetoothStateChangeCallback 1299 callback) { 1300 mCallback = callback; 1301 } 1302 1303 @Override 1304 public void onBluetoothStateChange(boolean on) { 1305 mCallback.onBluetoothStateChange(on); 1306 } 1307 } 1308 1309 private Set<BluetoothDevice> toDeviceSet(BluetoothDevice[] devices) { 1310 Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(Arrays.asList(devices)); 1311 return Collections.unmodifiableSet(deviceSet); 1312 } 1313 1314 protected void finalize() throws Throwable { 1315 try { 1316 mManagerService.unregisterAdapter(mManagerCallback); 1317 } catch (RemoteException e) { 1318 Log.e(TAG, "", e); 1319 } finally { 1320 super.finalize(); 1321 } 1322 } 1323 1324 1325 /** 1326 * Validate a String Bluetooth address, such as "00:43:A8:23:10:F0" 1327 * <p>Alphabetic characters must be uppercase to be valid. 1328 * 1329 * @param address Bluetooth address as string 1330 * @return true if the address is valid, false otherwise 1331 */ 1332 public static boolean checkBluetoothAddress(String address) { 1333 if (address == null || address.length() != ADDRESS_LENGTH) { 1334 return false; 1335 } 1336 for (int i = 0; i < ADDRESS_LENGTH; i++) { 1337 char c = address.charAt(i); 1338 switch (i % 3) { 1339 case 0: 1340 case 1: 1341 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) { 1342 // hex character, OK 1343 break; 1344 } 1345 return false; 1346 case 2: 1347 if (c == ':') { 1348 break; // OK 1349 } 1350 return false; 1351 } 1352 } 1353 return true; 1354 } 1355 1356 /*package*/ IBluetoothManager getBluetoothManager() { 1357 return mManagerService; 1358 } 1359 1360 /*package*/ IBluetooth getBluetoothService() { 1361 synchronized (mManagerCallback) { 1362 return mService; 1363 } 1364 } 1365} 1366