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