BluetoothAdapter.java revision fffa86ba834d37684238c83c0dd081133324984d
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 if (isEnabled() == true){ 508 if (DBG) Log.d(TAG, "enable(): BT is already enabled..!"); 509 return true; 510 } 511 try { 512 return mManagerService.enable(); 513 } catch (RemoteException e) {Log.e(TAG, "", e);} 514 return false; 515 } 516 517 /** 518 * Turn off the local Bluetooth adapter—do not use without explicit 519 * user action to turn off Bluetooth. 520 * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth 521 * system services, and powers down the underlying Bluetooth hardware. 522 * <p class="caution"><strong>Bluetooth should never be disabled without 523 * direct user consent</strong>. The {@link #disable()} method is 524 * provided only for applications that include a user interface for changing 525 * system settings, such as a "power manager" app.</p> 526 * <p>This is an asynchronous call: it will return immediately, and 527 * clients should listen for {@link #ACTION_STATE_CHANGED} 528 * to be notified of subsequent adapter state changes. If this call returns 529 * true, then the adapter state will immediately transition from {@link 530 * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time 531 * later transition to either {@link #STATE_OFF} or {@link 532 * #STATE_ON}. If this call returns false then there was an 533 * immediate problem that will prevent the adapter from being turned off - 534 * such as the adapter already being turned off. 535 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 536 * permission 537 * 538 * @return true to indicate adapter shutdown has begun, or false on 539 * immediate error 540 */ 541 public boolean disable() { 542 try { 543 return mManagerService.disable(true); 544 } catch (RemoteException e) {Log.e(TAG, "", e);} 545 return false; 546 } 547 548 /** 549 * Turn off the local Bluetooth adapter and don't persist the setting. 550 * 551 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 552 * permission 553 * 554 * @return true to indicate adapter shutdown has begun, or false on 555 * immediate error 556 * @hide 557 */ 558 public boolean disable(boolean persist) { 559 560 try { 561 return mManagerService.disable(persist); 562 } catch (RemoteException e) {Log.e(TAG, "", e);} 563 return false; 564 } 565 566 /** 567 * Returns the hardware address of the local Bluetooth adapter. 568 * <p>For example, "00:11:22:AA:BB:CC". 569 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 570 * 571 * @return Bluetooth hardware address as string 572 */ 573 public String getAddress() { 574 try { 575 return mManagerService.getAddress(); 576 } catch (RemoteException e) {Log.e(TAG, "", e);} 577 return null; 578 } 579 580 /** 581 * Get the friendly Bluetooth name of the local Bluetooth adapter. 582 * <p>This name is visible to remote Bluetooth devices. 583 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 584 * 585 * @return the Bluetooth name, or null on error 586 */ 587 public String getName() { 588 try { 589 return mManagerService.getName(); 590 } catch (RemoteException e) {Log.e(TAG, "", e);} 591 return null; 592 } 593 594 /** 595 * Get the UUIDs supported by the local Bluetooth adapter. 596 * 597 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 598 * 599 * @return the UUIDs supported by the local Bluetooth Adapter. 600 * @hide 601 */ 602 public ParcelUuid[] getUuids() { 603 if (getState() != STATE_ON) return null; 604 try { 605 synchronized(mManagerCallback) { 606 if (mService != null) return mService.getUuids(); 607 } 608 } catch (RemoteException e) {Log.e(TAG, "", e);} 609 return null; 610 } 611 612 /** 613 * Set the friendly Bluetooth name of the local Bluetooth adapter. 614 * <p>This name is visible to remote Bluetooth devices. 615 * <p>Valid Bluetooth names are a maximum of 248 bytes using UTF-8 616 * encoding, although many remote devices can only display the first 617 * 40 characters, and some may be limited to just 20. 618 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 619 * will return false. After turning on Bluetooth, 620 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 621 * to get the updated value. 622 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} 623 * 624 * @param name a valid Bluetooth name 625 * @return true if the name was set, false otherwise 626 */ 627 public boolean setName(String name) { 628 if (getState() != STATE_ON) return false; 629 try { 630 synchronized(mManagerCallback) { 631 if (mService != null) return mService.setName(name); 632 } 633 } catch (RemoteException e) {Log.e(TAG, "", e);} 634 return false; 635 } 636 637 /** 638 * Get the current Bluetooth scan mode of the local Bluetooth adapter. 639 * <p>The Bluetooth scan mode determines if the local adapter is 640 * connectable and/or discoverable from remote Bluetooth devices. 641 * <p>Possible values are: 642 * {@link #SCAN_MODE_NONE}, 643 * {@link #SCAN_MODE_CONNECTABLE}, 644 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. 645 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 646 * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth, 647 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 648 * to get the updated value. 649 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 650 * 651 * @return scan mode 652 */ 653 public int getScanMode() { 654 if (getState() != STATE_ON) return SCAN_MODE_NONE; 655 try { 656 synchronized(mManagerCallback) { 657 if (mService != null) return mService.getScanMode(); 658 } 659 } catch (RemoteException e) {Log.e(TAG, "", e);} 660 return SCAN_MODE_NONE; 661 } 662 663 /** 664 * Set the Bluetooth scan mode of the local Bluetooth adapter. 665 * <p>The Bluetooth scan mode determines if the local adapter is 666 * connectable and/or discoverable from remote Bluetooth devices. 667 * <p>For privacy reasons, discoverable mode is automatically turned off 668 * after <code>duration</code> seconds. For example, 120 seconds should be 669 * enough for a remote device to initiate and complete its discovery 670 * process. 671 * <p>Valid scan mode values are: 672 * {@link #SCAN_MODE_NONE}, 673 * {@link #SCAN_MODE_CONNECTABLE}, 674 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. 675 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 676 * will return false. After turning on Bluetooth, 677 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 678 * to get the updated value. 679 * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} 680 * <p>Applications cannot set the scan mode. They should use 681 * <code>startActivityForResult( 682 * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE}) 683 * </code>instead. 684 * 685 * @param mode valid scan mode 686 * @param duration time in seconds to apply scan mode, only used for 687 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE} 688 * @return true if the scan mode was set, false otherwise 689 * @hide 690 */ 691 public boolean setScanMode(int mode, int duration) { 692 if (getState() != STATE_ON) return false; 693 try { 694 synchronized(mManagerCallback) { 695 if (mService != null) return mService.setScanMode(mode, duration); 696 } 697 } catch (RemoteException e) {Log.e(TAG, "", e);} 698 return false; 699 } 700 701 /** @hide */ 702 public boolean setScanMode(int mode) { 703 if (getState() != STATE_ON) return false; 704 /* getDiscoverableTimeout() to use the latest from NV than use 0 */ 705 return setScanMode(mode, getDiscoverableTimeout()); 706 } 707 708 /** @hide */ 709 public int getDiscoverableTimeout() { 710 if (getState() != STATE_ON) return -1; 711 try { 712 synchronized(mManagerCallback) { 713 if (mService != null) return mService.getDiscoverableTimeout(); 714 } 715 } catch (RemoteException e) {Log.e(TAG, "", e);} 716 return -1; 717 } 718 719 /** @hide */ 720 public void setDiscoverableTimeout(int timeout) { 721 if (getState() != STATE_ON) return; 722 try { 723 synchronized(mManagerCallback) { 724 if (mService != null) mService.setDiscoverableTimeout(timeout); 725 } 726 } catch (RemoteException e) {Log.e(TAG, "", e);} 727 } 728 729 /** 730 * Start the remote device discovery process. 731 * <p>The discovery process usually involves an inquiry scan of about 12 732 * seconds, followed by a page scan of each new device to retrieve its 733 * Bluetooth name. 734 * <p>This is an asynchronous call, it will return immediately. Register 735 * for {@link #ACTION_DISCOVERY_STARTED} and {@link 736 * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the 737 * discovery starts and completes. Register for {@link 738 * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices 739 * are found. 740 * <p>Device discovery is a heavyweight procedure. New connections to 741 * remote Bluetooth devices should not be attempted while discovery is in 742 * progress, and existing connections will experience limited bandwidth 743 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 744 * discovery. Discovery is not managed by the Activity, 745 * but is run as a system service, so an application should always call 746 * {@link BluetoothAdapter#cancelDiscovery()} even if it 747 * did not directly request a discovery, just to be sure. 748 * <p>Device discovery will only find remote devices that are currently 749 * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are 750 * not discoverable by default, and need to be entered into a special mode. 751 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 752 * will return false. After turning on Bluetooth, 753 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 754 * to get the updated value. 755 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}. 756 * 757 * @return true on success, false on error 758 */ 759 public boolean startDiscovery() { 760 if (getState() != STATE_ON) return false; 761 try { 762 synchronized(mManagerCallback) { 763 if (mService != null) return mService.startDiscovery(); 764 } 765 } catch (RemoteException e) {Log.e(TAG, "", e);} 766 return false; 767 } 768 769 /** 770 * Cancel the current device discovery process. 771 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}. 772 * <p>Because discovery is a heavyweight procedure for the Bluetooth 773 * adapter, this method should always be called before attempting to connect 774 * to a remote device with {@link 775 * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by 776 * the Activity, but is run as a system service, so an application should 777 * always call cancel discovery even if it did not directly request a 778 * discovery, just to be sure. 779 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 780 * will return false. After turning on Bluetooth, 781 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 782 * to get the updated value. 783 * 784 * @return true on success, false on error 785 */ 786 public boolean cancelDiscovery() { 787 if (getState() != STATE_ON) return false; 788 try { 789 synchronized(mManagerCallback) { 790 if (mService != null) return mService.cancelDiscovery(); 791 } 792 } catch (RemoteException e) {Log.e(TAG, "", e);} 793 return false; 794 } 795 796 /** 797 * Return true if the local Bluetooth adapter is currently in the device 798 * discovery process. 799 * <p>Device discovery is a heavyweight procedure. New connections to 800 * remote Bluetooth devices should not be attempted while discovery is in 801 * progress, and existing connections will experience limited bandwidth 802 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 803 * discovery. 804 * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED} 805 * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery 806 * starts or completes. 807 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 808 * will return false. After turning on Bluetooth, 809 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 810 * to get the updated value. 811 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 812 * 813 * @return true if discovering 814 */ 815 public boolean isDiscovering() { 816 if (getState() != STATE_ON) return false; 817 try { 818 synchronized(mManagerCallback) { 819 if (mService != null ) return mService.isDiscovering(); 820 } 821 } catch (RemoteException e) {Log.e(TAG, "", e);} 822 return false; 823 } 824 825 /** 826 * Return the set of {@link BluetoothDevice} objects that are bonded 827 * (paired) to the local adapter. 828 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 829 * will return an empty set. After turning on Bluetooth, 830 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 831 * to get the updated value. 832 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 833 * 834 * @return unmodifiable set of {@link BluetoothDevice}, or null on error 835 */ 836 public Set<BluetoothDevice> getBondedDevices() { 837 if (getState() != STATE_ON) { 838 return toDeviceSet(new BluetoothDevice[0]); 839 } 840 try { 841 synchronized(mManagerCallback) { 842 if (mService != null) return toDeviceSet(mService.getBondedDevices()); 843 } 844 return toDeviceSet(new BluetoothDevice[0]); 845 } catch (RemoteException e) {Log.e(TAG, "", e);} 846 return null; 847 } 848 849 /** 850 * Get the current connection state of the local Bluetooth adapter. 851 * This can be used to check whether the local Bluetooth adapter is connected 852 * to any profile of any other remote Bluetooth Device. 853 * 854 * <p> Use this function along with {@link #ACTION_CONNECTION_STATE_CHANGED} 855 * intent to get the connection state of the adapter. 856 * 857 * @return One of {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTED}, 858 * {@link #STATE_CONNECTING} or {@link #STATE_DISCONNECTED} 859 * 860 * @hide 861 */ 862 public int getConnectionState() { 863 if (getState() != STATE_ON) return BluetoothAdapter.STATE_DISCONNECTED; 864 try { 865 synchronized(mManagerCallback) { 866 if (mService != null) return mService.getAdapterConnectionState(); 867 } 868 } catch (RemoteException e) {Log.e(TAG, "getConnectionState:", e);} 869 return BluetoothAdapter.STATE_DISCONNECTED; 870 } 871 872 /** 873 * Get the current connection state of a profile. 874 * This function can be used to check whether the local Bluetooth adapter 875 * is connected to any remote device for a specific profile. 876 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET}, 877 * {@link BluetoothProfile#A2DP}. 878 * 879 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 880 * 881 * <p> Return value can be one of 882 * {@link BluetoothProfile#STATE_DISCONNECTED}, 883 * {@link BluetoothProfile#STATE_CONNECTING}, 884 * {@link BluetoothProfile#STATE_CONNECTED}, 885 * {@link BluetoothProfile#STATE_DISCONNECTING} 886 */ 887 public int getProfileConnectionState(int profile) { 888 if (getState() != STATE_ON) return BluetoothProfile.STATE_DISCONNECTED; 889 try { 890 synchronized(mManagerCallback) { 891 if (mService != null) return mService.getProfileConnectionState(profile); 892 } 893 } catch (RemoteException e) { 894 Log.e(TAG, "getProfileConnectionState:", e); 895 } 896 return BluetoothProfile.STATE_DISCONNECTED; 897 } 898 899 /** 900 * Create a listening, secure RFCOMM Bluetooth socket. 901 * <p>A remote device connecting to this socket will be authenticated and 902 * communication on this socket will be encrypted. 903 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 904 * connections from a listening {@link BluetoothServerSocket}. 905 * <p>Valid RFCOMM channels are in range 1 to 30. 906 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} 907 * @param channel RFCOMM channel to listen on 908 * @return a listening RFCOMM BluetoothServerSocket 909 * @throws IOException on error, for example Bluetooth not available, or 910 * insufficient permissions, or channel in use. 911 * @hide 912 */ 913 public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException { 914 BluetoothServerSocket socket = new BluetoothServerSocket( 915 BluetoothSocket.TYPE_RFCOMM, true, true, channel); 916 int errno = socket.mSocket.bindListen(); 917 if (errno != 0) { 918 //TODO(BT): Throw the same exception error code 919 // that the previous code was using. 920 //socket.mSocket.throwErrnoNative(errno); 921 throw new IOException("Error: " + errno); 922 } 923 return socket; 924 } 925 926 /** 927 * Create a listening, secure RFCOMM Bluetooth socket with Service Record. 928 * <p>A remote device connecting to this socket will be authenticated and 929 * communication on this socket will be encrypted. 930 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 931 * connections from a listening {@link BluetoothServerSocket}. 932 * <p>The system will assign an unused RFCOMM channel to listen on. 933 * <p>The system will also register a Service Discovery 934 * Protocol (SDP) record with the local SDP server containing the specified 935 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 936 * can use the same UUID to query our SDP server and discover which channel 937 * to connect to. This SDP record will be removed when this socket is 938 * closed, or if this application closes unexpectedly. 939 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 940 * connect to this socket from another device using the same {@link UUID}. 941 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 942 * @param name service name for SDP record 943 * @param uuid uuid for SDP record 944 * @return a listening RFCOMM BluetoothServerSocket 945 * @throws IOException on error, for example Bluetooth not available, or 946 * insufficient permissions, or channel in use. 947 */ 948 public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid) 949 throws IOException { 950 return createNewRfcommSocketAndRecord(name, uuid, true, true); 951 } 952 953 /** 954 * Create a listening, insecure RFCOMM Bluetooth socket with Service Record. 955 * <p>The link key is not required to be authenticated, i.e the communication may be 956 * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices, 957 * the link will be encrypted, as encryption is mandartory. 958 * For legacy devices (pre Bluetooth 2.1 devices) the link will not 959 * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an 960 * encrypted and authenticated communication channel is desired. 961 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 962 * connections from a listening {@link BluetoothServerSocket}. 963 * <p>The system will assign an unused RFCOMM channel to listen on. 964 * <p>The system will also register a Service Discovery 965 * Protocol (SDP) record with the local SDP server containing the specified 966 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 967 * can use the same UUID to query our SDP server and discover which channel 968 * to connect to. This SDP record will be removed when this socket is 969 * closed, or if this application closes unexpectedly. 970 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 971 * connect to this socket from another device using the same {@link UUID}. 972 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 973 * @param name service name for SDP record 974 * @param uuid uuid for SDP record 975 * @return a listening RFCOMM BluetoothServerSocket 976 * @throws IOException on error, for example Bluetooth not available, or 977 * insufficient permissions, or channel in use. 978 */ 979 public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid) 980 throws IOException { 981 return createNewRfcommSocketAndRecord(name, uuid, false, false); 982 } 983 984 /** 985 * Create a listening, encrypted, 986 * RFCOMM Bluetooth socket with Service Record. 987 * <p>The link will be encrypted, but the link key is not required to be authenticated 988 * i.e the communication is vulnerable to Man In the Middle attacks. Use 989 * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key. 990 * <p> Use this socket if authentication of link key is not possible. 991 * For example, for Bluetooth 2.1 devices, if any of the devices does not have 992 * an input and output capability or just has the ability to display a numeric key, 993 * a secure socket connection is not possible and this socket can be used. 994 * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required. 995 * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory. 996 * For more details, refer to the Security Model section 5.2 (vol 3) of 997 * Bluetooth Core Specification version 2.1 + EDR. 998 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 999 * connections from a listening {@link BluetoothServerSocket}. 1000 * <p>The system will assign an unused RFCOMM channel to listen on. 1001 * <p>The system will also register a Service Discovery 1002 * Protocol (SDP) record with the local SDP server containing the specified 1003 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 1004 * can use the same UUID to query our SDP server and discover which channel 1005 * to connect to. This SDP record will be removed when this socket is 1006 * closed, or if this application closes unexpectedly. 1007 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 1008 * connect to this socket from another device using the same {@link UUID}. 1009 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1010 * @param name service name for SDP record 1011 * @param uuid uuid for SDP record 1012 * @return a listening RFCOMM BluetoothServerSocket 1013 * @throws IOException on error, for example Bluetooth not available, or 1014 * insufficient permissions, or channel in use. 1015 * @hide 1016 */ 1017 public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord( 1018 String name, UUID uuid) throws IOException { 1019 return createNewRfcommSocketAndRecord(name, uuid, false, true); 1020 } 1021 1022 1023 private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid, 1024 boolean auth, boolean encrypt) throws IOException { 1025 BluetoothServerSocket socket; 1026 socket = new BluetoothServerSocket(BluetoothSocket.TYPE_RFCOMM, auth, 1027 encrypt, new ParcelUuid(uuid)); 1028 socket.setServiceName(name); 1029 int errno = socket.mSocket.bindListen(); 1030 if (errno != 0) { 1031 //TODO(BT): Throw the same exception error code 1032 // that the previous code was using. 1033 //socket.mSocket.throwErrnoNative(errno); 1034 throw new IOException("Error: " + errno); 1035 } 1036 return socket; 1037 } 1038 1039 /** 1040 * Construct an unencrypted, unauthenticated, RFCOMM server socket. 1041 * Call #accept to retrieve connections to this socket. 1042 * @return An RFCOMM BluetoothServerSocket 1043 * @throws IOException On error, for example Bluetooth not available, or 1044 * insufficient permissions. 1045 * @hide 1046 */ 1047 public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException { 1048 BluetoothServerSocket socket = new BluetoothServerSocket( 1049 BluetoothSocket.TYPE_RFCOMM, false, false, port); 1050 int errno = socket.mSocket.bindListen(); 1051 if (errno != 0) { 1052 //TODO(BT): Throw the same exception error code 1053 // that the previous code was using. 1054 //socket.mSocket.throwErrnoNative(errno); 1055 throw new IOException("Error: " + errno); 1056 } 1057 return socket; 1058 } 1059 1060 /** 1061 * Construct an encrypted, RFCOMM server socket. 1062 * Call #accept to retrieve connections to this socket. 1063 * @return An RFCOMM BluetoothServerSocket 1064 * @throws IOException On error, for example Bluetooth not available, or 1065 * insufficient permissions. 1066 * @hide 1067 */ 1068 public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port) 1069 throws IOException { 1070 BluetoothServerSocket socket = new BluetoothServerSocket( 1071 BluetoothSocket.TYPE_RFCOMM, false, true, port); 1072 int errno = socket.mSocket.bindListen(); 1073 if (errno < 0) { 1074 //TODO(BT): Throw the same exception error code 1075 // that the previous code was using. 1076 //socket.mSocket.throwErrnoNative(errno); 1077 throw new IOException("Error: " + errno); 1078 } 1079 return socket; 1080 } 1081 1082 /** 1083 * Construct a SCO server socket. 1084 * Call #accept to retrieve connections to this socket. 1085 * @return A SCO BluetoothServerSocket 1086 * @throws IOException On error, for example Bluetooth not available, or 1087 * insufficient permissions. 1088 * @hide 1089 */ 1090 public static BluetoothServerSocket listenUsingScoOn() throws IOException { 1091 BluetoothServerSocket socket = new BluetoothServerSocket( 1092 BluetoothSocket.TYPE_SCO, false, false, -1); 1093 int errno = socket.mSocket.bindListen(); 1094 if (errno < 0) { 1095 //TODO(BT): Throw the same exception error code 1096 // that the previous code was using. 1097 //socket.mSocket.throwErrnoNative(errno); 1098 } 1099 return socket; 1100 } 1101 1102 /** 1103 * Read the local Out of Band Pairing Data 1104 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1105 * 1106 * @return Pair<byte[], byte[]> of Hash and Randomizer 1107 * 1108 * @hide 1109 */ 1110 public Pair<byte[], byte[]> readOutOfBandData() { 1111 if (getState() != STATE_ON) return null; 1112 //TODO(BT 1113 /* 1114 try { 1115 byte[] hash; 1116 byte[] randomizer; 1117 1118 byte[] ret = mService.readOutOfBandData(); 1119 1120 if (ret == null || ret.length != 32) return null; 1121 1122 hash = Arrays.copyOfRange(ret, 0, 16); 1123 randomizer = Arrays.copyOfRange(ret, 16, 32); 1124 1125 if (DBG) { 1126 Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) + 1127 ":" + Arrays.toString(randomizer)); 1128 } 1129 return new Pair<byte[], byte[]>(hash, randomizer); 1130 1131 } catch (RemoteException e) {Log.e(TAG, "", e);}*/ 1132 return null; 1133 } 1134 1135 /** 1136 * Get the profile proxy object associated with the profile. 1137 * 1138 * <p>Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or 1139 * {@link BluetoothProfile#A2DP}. Clients must implements 1140 * {@link BluetoothProfile.ServiceListener} to get notified of 1141 * the connection status and to get the proxy object. 1142 * 1143 * @param context Context of the application 1144 * @param listener The service Listener for connection callbacks. 1145 * @param profile The Bluetooth profile; either {@link BluetoothProfile#HEALTH}, 1146 * {@link BluetoothProfile#HEADSET} or {@link BluetoothProfile#A2DP}. 1147 * @return true on success, false on error 1148 */ 1149 public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener, 1150 int profile) { 1151 if (context == null || listener == null) return false; 1152 1153 if (profile == BluetoothProfile.HEADSET) { 1154 BluetoothHeadset headset = new BluetoothHeadset(context, listener); 1155 return true; 1156 } else if (profile == BluetoothProfile.A2DP) { 1157 BluetoothA2dp a2dp = new BluetoothA2dp(context, listener); 1158 return true; 1159 } else if (profile == BluetoothProfile.INPUT_DEVICE) { 1160 BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener); 1161 return true; 1162 } else if (profile == BluetoothProfile.PAN) { 1163 BluetoothPan pan = new BluetoothPan(context, listener); 1164 return true; 1165 } else if (profile == BluetoothProfile.HEALTH) { 1166 BluetoothHealth health = new BluetoothHealth(context, listener); 1167 return true; 1168 } else { 1169 return false; 1170 } 1171 } 1172 1173 /** 1174 * Close the connection of the profile proxy to the Service. 1175 * 1176 * <p> Clients should call this when they are no longer using 1177 * the proxy obtained from {@link #getProfileProxy}. 1178 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or 1179 * {@link BluetoothProfile#A2DP} 1180 * 1181 * @param profile 1182 * @param proxy Profile proxy object 1183 */ 1184 public void closeProfileProxy(int profile, BluetoothProfile proxy) { 1185 if (proxy == null) return; 1186 1187 switch (profile) { 1188 case BluetoothProfile.HEADSET: 1189 BluetoothHeadset headset = (BluetoothHeadset)proxy; 1190 headset.close(); 1191 break; 1192 case BluetoothProfile.A2DP: 1193 BluetoothA2dp a2dp = (BluetoothA2dp)proxy; 1194 a2dp.close(); 1195 break; 1196 case BluetoothProfile.INPUT_DEVICE: 1197 BluetoothInputDevice iDev = (BluetoothInputDevice)proxy; 1198 iDev.close(); 1199 break; 1200 case BluetoothProfile.PAN: 1201 BluetoothPan pan = (BluetoothPan)proxy; 1202 pan.close(); 1203 break; 1204 case BluetoothProfile.HEALTH: 1205 BluetoothHealth health = (BluetoothHealth)proxy; 1206 health.close(); 1207 break; 1208 } 1209 } 1210 1211 final private IBluetoothManagerCallback mManagerCallback = 1212 new IBluetoothManagerCallback.Stub() { 1213 public void onBluetoothServiceUp(IBluetooth bluetoothService) { 1214 if (DBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService); 1215 synchronized (mManagerCallback) { 1216 mService = bluetoothService; 1217 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){ 1218 try { 1219 if (cb != null) { 1220 cb.onBluetoothServiceUp(bluetoothService); 1221 } else { 1222 Log.d(TAG, "onBluetoothServiceUp: cb is null!!!"); 1223 } 1224 } catch (Exception e) { Log.e(TAG,"",e);} 1225 } 1226 } 1227 } 1228 1229 public void onBluetoothServiceDown() { 1230 if (DBG) Log.d(TAG, "onBluetoothServiceDown: " + mService); 1231 synchronized (mManagerCallback) { 1232 mService = null; 1233 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){ 1234 try { 1235 if (cb != null) { 1236 cb.onBluetoothServiceDown(); 1237 } else { 1238 Log.d(TAG, "onBluetoothServiceDown: cb is null!!!"); 1239 } 1240 } catch (Exception e) { Log.e(TAG,"",e);} 1241 } 1242 } 1243 } 1244 }; 1245 1246 /** 1247 * Enable the Bluetooth Adapter, but don't auto-connect devices 1248 * and don't persist state. Only for use by system applications. 1249 * @hide 1250 */ 1251 public boolean enableNoAutoConnect() { 1252 if (isEnabled() == true){ 1253 if (DBG) Log.d(TAG, "enableNoAutoConnect(): BT is already enabled..!"); 1254 return true; 1255 } 1256 try { 1257 return mManagerService.enableNoAutoConnect(); 1258 } catch (RemoteException e) {Log.e(TAG, "", e);} 1259 return false; 1260 } 1261 1262 /** 1263 * Enable control of the Bluetooth Adapter for a single application. 1264 * 1265 * <p>Some applications need to use Bluetooth for short periods of time to 1266 * transfer data but don't want all the associated implications like 1267 * automatic connection to headsets etc. 1268 * 1269 * <p> Multiple applications can call this. This is reference counted and 1270 * Bluetooth disabled only when no one else is using it. There will be no UI 1271 * shown to the user while bluetooth is being enabled. Any user action will 1272 * override this call. For example, if user wants Bluetooth on and the last 1273 * user of this API wanted to disable Bluetooth, Bluetooth will not be 1274 * turned off. 1275 * 1276 * <p> This API is only meant to be used by internal applications. Third 1277 * party applications but use {@link #enable} and {@link #disable} APIs. 1278 * 1279 * <p> If this API returns true, it means the callback will be called. 1280 * The callback will be called with the current state of Bluetooth. 1281 * If the state is not what was requested, an internal error would be the 1282 * reason. If Bluetooth is already on and if this function is called to turn 1283 * it on, the api will return true and a callback will be called. 1284 * 1285 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 1286 * 1287 * @param on True for on, false for off. 1288 * @param callback The callback to notify changes to the state. 1289 * @hide 1290 */ 1291 public boolean changeApplicationBluetoothState(boolean on, 1292 BluetoothStateChangeCallback callback) { 1293 if (callback == null) return false; 1294 1295 //TODO(BT) 1296 /* 1297 try { 1298 return mService.changeApplicationBluetoothState(on, new 1299 StateChangeCallbackWrapper(callback), new Binder()); 1300 } catch (RemoteException e) { 1301 Log.e(TAG, "changeBluetoothState", e); 1302 }*/ 1303 return false; 1304 } 1305 1306 /** 1307 * @hide 1308 */ 1309 public interface BluetoothStateChangeCallback { 1310 public void onBluetoothStateChange(boolean on); 1311 } 1312 1313 /** 1314 * @hide 1315 */ 1316 public class StateChangeCallbackWrapper extends IBluetoothStateChangeCallback.Stub { 1317 private BluetoothStateChangeCallback mCallback; 1318 1319 StateChangeCallbackWrapper(BluetoothStateChangeCallback 1320 callback) { 1321 mCallback = callback; 1322 } 1323 1324 @Override 1325 public void onBluetoothStateChange(boolean on) { 1326 mCallback.onBluetoothStateChange(on); 1327 } 1328 } 1329 1330 private Set<BluetoothDevice> toDeviceSet(BluetoothDevice[] devices) { 1331 Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(Arrays.asList(devices)); 1332 return Collections.unmodifiableSet(deviceSet); 1333 } 1334 1335 protected void finalize() throws Throwable { 1336 try { 1337 mManagerService.unregisterAdapter(mManagerCallback); 1338 } catch (RemoteException e) { 1339 Log.e(TAG, "", e); 1340 } finally { 1341 super.finalize(); 1342 } 1343 } 1344 1345 1346 /** 1347 * Validate a String Bluetooth address, such as "00:43:A8:23:10:F0" 1348 * <p>Alphabetic characters must be uppercase to be valid. 1349 * 1350 * @param address Bluetooth address as string 1351 * @return true if the address is valid, false otherwise 1352 */ 1353 public static boolean checkBluetoothAddress(String address) { 1354 if (address == null || address.length() != ADDRESS_LENGTH) { 1355 return false; 1356 } 1357 for (int i = 0; i < ADDRESS_LENGTH; i++) { 1358 char c = address.charAt(i); 1359 switch (i % 3) { 1360 case 0: 1361 case 1: 1362 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) { 1363 // hex character, OK 1364 break; 1365 } 1366 return false; 1367 case 2: 1368 if (c == ':') { 1369 break; // OK 1370 } 1371 return false; 1372 } 1373 } 1374 return true; 1375 } 1376 1377 /*package*/ IBluetoothManager getBluetoothManager() { 1378 return mManagerService; 1379 } 1380 1381 private ArrayList<IBluetoothManagerCallback> mProxyServiceStateCallbacks = new ArrayList<IBluetoothManagerCallback>(); 1382 1383 /*package*/ IBluetooth getBluetoothService(IBluetoothManagerCallback cb) { 1384 synchronized (mManagerCallback) { 1385 if (cb == null) { 1386 Log.w(TAG, "getBluetoothService() called with no BluetoothManagerCallback"); 1387 } else if (!mProxyServiceStateCallbacks.contains(cb)) { 1388 mProxyServiceStateCallbacks.add(cb); 1389 } 1390 } 1391 return mService; 1392 } 1393 1394 /*package*/ void removeServiceStateCallback(IBluetoothManagerCallback cb) { 1395 synchronized (mManagerCallback) { 1396 mProxyServiceStateCallbacks.remove(cb); 1397 } 1398 } 1399} 1400