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