BluetoothAdapter.java revision c53cab20b225ba69057441ecb06db6478ab8ff9b
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.Message; 26import android.os.ParcelUuid; 27import android.os.RemoteException; 28import android.os.ServiceManager; 29import android.util.Log; 30import android.util.Pair; 31 32import java.io.IOException; 33import java.util.Arrays; 34import java.util.Collections; 35import java.util.HashSet; 36import java.util.LinkedList; 37import java.util.Random; 38import java.util.Set; 39import java.util.UUID; 40 41/** 42 * Represents the local device Bluetooth adapter. The {@link BluetoothAdapter} 43 * lets you perform fundamental Bluetooth tasks, such as initiate 44 * device discovery, query a list of bonded (paired) devices, 45 * instantiate a {@link BluetoothDevice} using a known MAC address, and create 46 * a {@link BluetoothServerSocket} to listen for connection requests from other 47 * devices. 48 * 49 * <p>To get a {@link BluetoothAdapter} representing the local Bluetooth 50 * adapter, call the static {@link #getDefaultAdapter} method. 51 * Fundamentally, this is your starting point for all 52 * Bluetooth actions. Once you have the local adapter, you can get a set of 53 * {@link BluetoothDevice} objects representing all paired devices with 54 * {@link #getBondedDevices()}; start device discovery with 55 * {@link #startDiscovery()}; or create a {@link BluetoothServerSocket} to 56 * listen for incoming connection requests with 57 * {@link #listenUsingRfcommWithServiceRecord(String,UUID)}. 58 * 59 * <p class="note"><strong>Note:</strong> 60 * Most methods require the {@link android.Manifest.permission#BLUETOOTH} 61 * permission and some also require the 62 * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission. 63 * 64 * {@see BluetoothDevice} 65 * {@see BluetoothServerSocket} 66 */ 67public final class BluetoothAdapter { 68 private static final String TAG = "BluetoothAdapter"; 69 private static final boolean DBG = false; 70 71 /** 72 * Sentinel error value for this class. Guaranteed to not equal any other 73 * integer constant in this class. Provided as a convenience for functions 74 * that require a sentinel error value, for example: 75 * <p><code>Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 76 * BluetoothAdapter.ERROR)</code> 77 */ 78 public static final int ERROR = Integer.MIN_VALUE; 79 80 /** 81 * Broadcast Action: The state of the local Bluetooth adapter has been 82 * changed. 83 * <p>For example, Bluetooth has been turned on or off. 84 * <p>Always contains the extra fields {@link #EXTRA_STATE} and {@link 85 * #EXTRA_PREVIOUS_STATE} containing the new and old states 86 * respectively. 87 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 88 */ 89 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 90 public static final String ACTION_STATE_CHANGED = 91 "android.bluetooth.adapter.action.STATE_CHANGED"; 92 93 /** 94 * Used as an int extra field in {@link #ACTION_STATE_CHANGED} 95 * intents to request the current power state. Possible values are: 96 * {@link #STATE_OFF}, 97 * {@link #STATE_TURNING_ON}, 98 * {@link #STATE_ON}, 99 * {@link #STATE_TURNING_OFF}, 100 */ 101 public static final String EXTRA_STATE = 102 "android.bluetooth.adapter.extra.STATE"; 103 /** 104 * Used as an int extra field in {@link #ACTION_STATE_CHANGED} 105 * intents to request the previous power state. Possible values are: 106 * {@link #STATE_OFF}, 107 * {@link #STATE_TURNING_ON}, 108 * {@link #STATE_ON}, 109 * {@link #STATE_TURNING_OFF}, 110 */ 111 public static final String EXTRA_PREVIOUS_STATE = 112 "android.bluetooth.adapter.extra.PREVIOUS_STATE"; 113 114 /** 115 * Indicates the local Bluetooth adapter is off. 116 */ 117 public static final int STATE_OFF = 10; 118 /** 119 * Indicates the local Bluetooth adapter is turning on. However local 120 * clients should wait for {@link #STATE_ON} before attempting to 121 * use the adapter. 122 */ 123 public static final int STATE_TURNING_ON = 11; 124 /** 125 * Indicates the local Bluetooth adapter is on, and ready for use. 126 */ 127 public static final int STATE_ON = 12; 128 /** 129 * Indicates the local Bluetooth adapter is turning off. Local clients 130 * should immediately attempt graceful disconnection of any remote links. 131 */ 132 public static final int STATE_TURNING_OFF = 13; 133 134 /** 135 * Activity Action: Show a system activity that requests discoverable mode. 136 * This activity will also request the user to turn on Bluetooth if it 137 * is not currently enabled. 138 * <p>Discoverable mode is equivalent to {@link 139 * #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. It allows remote devices to see 140 * this Bluetooth adapter when they perform a discovery. 141 * <p>For privacy, Android is not discoverable by default. 142 * <p>The sender of this Intent can optionally use extra field {@link 143 * #EXTRA_DISCOVERABLE_DURATION} to request the duration of 144 * discoverability. Currently the default duration is 120 seconds, and 145 * maximum duration is capped at 300 seconds for each request. 146 * <p>Notification of the result of this activity is posted using the 147 * {@link android.app.Activity#onActivityResult} callback. The 148 * <code>resultCode</code> 149 * will be the duration (in seconds) of discoverability or 150 * {@link android.app.Activity#RESULT_CANCELED} if the user rejected 151 * discoverability or an error has occurred. 152 * <p>Applications can also listen for {@link #ACTION_SCAN_MODE_CHANGED} 153 * for global notification whenever the scan mode changes. For example, an 154 * application can be notified when the device has ended discoverability. 155 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 156 */ 157 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 158 public static final String ACTION_REQUEST_DISCOVERABLE = 159 "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE"; 160 161 /** 162 * Used as an optional int extra field in {@link 163 * #ACTION_REQUEST_DISCOVERABLE} intents to request a specific duration 164 * for discoverability in seconds. The current default is 120 seconds, and 165 * requests over 300 seconds will be capped. These values could change. 166 */ 167 public static final String EXTRA_DISCOVERABLE_DURATION = 168 "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION"; 169 170 /** 171 * Activity Action: Show a system activity that allows the user to turn on 172 * Bluetooth. 173 * <p>This system activity will return once Bluetooth has completed turning 174 * on, or the user has decided not to turn Bluetooth on. 175 * <p>Notification of the result of this activity is posted using the 176 * {@link android.app.Activity#onActivityResult} callback. The 177 * <code>resultCode</code> 178 * will be {@link android.app.Activity#RESULT_OK} if Bluetooth has been 179 * turned on or {@link android.app.Activity#RESULT_CANCELED} if the user 180 * has rejected the request or an error has occurred. 181 * <p>Applications can also listen for {@link #ACTION_STATE_CHANGED} 182 * for global notification whenever Bluetooth is turned on or off. 183 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 184 */ 185 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 186 public static final String ACTION_REQUEST_ENABLE = 187 "android.bluetooth.adapter.action.REQUEST_ENABLE"; 188 189 /** 190 * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter 191 * has changed. 192 * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link 193 * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes 194 * respectively. 195 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 196 */ 197 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 198 public static final String ACTION_SCAN_MODE_CHANGED = 199 "android.bluetooth.adapter.action.SCAN_MODE_CHANGED"; 200 201 /** 202 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED} 203 * intents to request the current scan mode. Possible values are: 204 * {@link #SCAN_MODE_NONE}, 205 * {@link #SCAN_MODE_CONNECTABLE}, 206 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}, 207 */ 208 public static final String EXTRA_SCAN_MODE = "android.bluetooth.adapter.extra.SCAN_MODE"; 209 /** 210 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED} 211 * intents to request the previous 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_PREVIOUS_SCAN_MODE = 217 "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE"; 218 219 /** 220 * Indicates that both inquiry scan and page scan are disabled on the local 221 * Bluetooth adapter. Therefore this device is neither discoverable 222 * nor connectable from remote Bluetooth devices. 223 */ 224 public static final int SCAN_MODE_NONE = 20; 225 /** 226 * Indicates that inquiry scan is disabled, but page scan is enabled on the 227 * local Bluetooth adapter. Therefore this device is not discoverable from 228 * remote Bluetooth devices, but is connectable from remote devices that 229 * have previously discovered this device. 230 */ 231 public static final int SCAN_MODE_CONNECTABLE = 21; 232 /** 233 * Indicates that both inquiry scan and page scan are enabled on the local 234 * Bluetooth adapter. Therefore this device is both discoverable and 235 * connectable from remote Bluetooth devices. 236 */ 237 public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23; 238 239 240 /** 241 * Broadcast Action: The local Bluetooth adapter has started the remote 242 * device discovery process. 243 * <p>This usually involves an inquiry scan of about 12 seconds, followed 244 * by a page scan of each new device to retrieve its Bluetooth name. 245 * <p>Register for {@link BluetoothDevice#ACTION_FOUND} to be notified as 246 * remote Bluetooth devices are found. 247 * <p>Device discovery is a heavyweight procedure. New connections to 248 * remote Bluetooth devices should not be attempted while discovery is in 249 * progress, and existing connections will experience limited bandwidth 250 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 251 * discovery. 252 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 253 */ 254 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 255 public static final String ACTION_DISCOVERY_STARTED = 256 "android.bluetooth.adapter.action.DISCOVERY_STARTED"; 257 /** 258 * Broadcast Action: The local Bluetooth adapter has finished the device 259 * discovery process. 260 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 261 */ 262 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 263 public static final String ACTION_DISCOVERY_FINISHED = 264 "android.bluetooth.adapter.action.DISCOVERY_FINISHED"; 265 266 /** 267 * Broadcast Action: The local Bluetooth adapter has changed its friendly 268 * Bluetooth name. 269 * <p>This name is visible to remote Bluetooth devices. 270 * <p>Always contains the extra field {@link #EXTRA_LOCAL_NAME} containing 271 * the name. 272 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 273 */ 274 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 275 public static final String ACTION_LOCAL_NAME_CHANGED = 276 "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED"; 277 /** 278 * Used as a String extra field in {@link #ACTION_LOCAL_NAME_CHANGED} 279 * intents to request the local Bluetooth name. 280 */ 281 public static final String EXTRA_LOCAL_NAME = "android.bluetooth.adapter.extra.LOCAL_NAME"; 282 283 /** 284 * Intent used to broadcast the change in connection state of the local 285 * Bluetooth adapter to a profile of the remote device. When the adapter is 286 * not connected to any profiles of any remote devices and it attempts a 287 * connection to a profile this intent will sent. Once connected, this intent 288 * will not be sent for any more connection attempts to any profiles of any 289 * remote device. When the adapter disconnects from the last profile its 290 * connected to of any remote device, this intent will be sent. 291 * 292 * <p> This intent is useful for applications that are only concerned about 293 * whether the local adapter is connected to any profile of any device and 294 * are not really concerned about which profile. For example, an application 295 * which displays an icon to display whether Bluetooth is connected or not 296 * can use this intent. 297 * 298 * <p>This intent will have 3 extras: 299 * {@link #EXTRA_STATE} - The current state. 300 * {@link #EXTRA_PREVIOUS_STATE}- The previous. 301 * {@link BluetoothDevice#EXTRA_DEVICE} - The remote device. 302 * 303 * {@link #EXTRA_STATE} or {@link #EXTRA_PREVIOUS_STATE} can be any of 304 * {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING}, 305 * {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}. 306 * 307 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive. 308 */ 309 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 310 public static final String ACTION_CONNECTION_STATE_CHANGED = 311 "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED"; 312 313 /** 314 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED} 315 * 316 * This extra represents the current connection state. 317 */ 318 public static final String EXTRA_CONNECTION_STATE = 319 "android.bluetooth.adapter.extra.CONNECTION_STATE"; 320 321 /** 322 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED} 323 * 324 * This extra represents the previous connection state. 325 */ 326 public static final String EXTRA_PREVIOUS_CONNECTION_STATE = 327 "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE"; 328 329 /** The profile is in disconnected state */ 330 public static final int STATE_DISCONNECTED = 0; 331 /** The profile is in connecting state */ 332 public static final int STATE_CONNECTING = 1; 333 /** The profile is in connected state */ 334 public static final int STATE_CONNECTED = 2; 335 /** The profile is in disconnecting state */ 336 public static final int STATE_DISCONNECTING = 3; 337 338 /** @hide */ 339 public static final String BLUETOOTH_SERVICE = "bluetooth"; 340 341 private static final int ADDRESS_LENGTH = 17; 342 343 /** 344 * Lazily initialized singleton. Guaranteed final after first object 345 * constructed. 346 */ 347 private static BluetoothAdapter sAdapter; 348 349 private final IBluetooth mService; 350 351 /** 352 * Get a handle to the default local Bluetooth adapter. 353 * <p>Currently Android only supports one Bluetooth adapter, but the API 354 * could be extended to support more. This will always return the default 355 * adapter. 356 * @return the default local adapter, or null if Bluetooth is not supported 357 * on this hardware platform 358 */ 359 public static synchronized BluetoothAdapter getDefaultAdapter() { 360 if (sAdapter == null) { 361 IBinder b = ServiceManager.getService(BluetoothAdapter.BLUETOOTH_SERVICE); 362 if (b != null) { 363 IBluetooth service = IBluetooth.Stub.asInterface(b); 364 sAdapter = new BluetoothAdapter(service); 365 } 366 } 367 return sAdapter; 368 } 369 370 /** 371 * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance. 372 * @hide 373 */ 374 public BluetoothAdapter(IBluetooth service) { 375 if (service == null) { 376 throw new IllegalArgumentException("service is null"); 377 } 378 mService = service; 379 } 380 381 /** 382 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware 383 * address. 384 * <p>Valid Bluetooth hardware addresses must be upper case, in a format 385 * such as "00:11:22:33:AA:BB". The helper {@link #checkBluetoothAddress} is 386 * available to validate a Bluetooth address. 387 * <p>A {@link BluetoothDevice} will always be returned for a valid 388 * hardware address, even if this adapter has never seen that device. 389 * 390 * @param address valid Bluetooth MAC address 391 * @throws IllegalArgumentException if address is invalid 392 */ 393 public BluetoothDevice getRemoteDevice(String address) { 394 return new BluetoothDevice(address); 395 } 396 397 /** 398 * Return true if Bluetooth is currently enabled and ready for use. 399 * <p>Equivalent to: 400 * <code>getBluetoothState() == STATE_ON</code> 401 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 402 * 403 * @return true if the local adapter is turned on 404 */ 405 public boolean isEnabled() { 406 try { 407 return mService.isEnabled(); 408 } catch (RemoteException e) {Log.e(TAG, "", e);} 409 return false; 410 } 411 412 /** 413 * Get the current state of the local Bluetooth adapter. 414 * <p>Possible return values are 415 * {@link #STATE_OFF}, 416 * {@link #STATE_TURNING_ON}, 417 * {@link #STATE_ON}, 418 * {@link #STATE_TURNING_OFF}. 419 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 420 * 421 * @return current state of Bluetooth adapter 422 */ 423 public int getState() { 424 try { 425 return mService.getBluetoothState(); 426 } catch (RemoteException e) {Log.e(TAG, "", e);} 427 return STATE_OFF; 428 } 429 430 /** 431 * Turn on the local Bluetooth adapter—do not use without explicit 432 * user action to turn on Bluetooth. 433 * <p>This powers on the underlying Bluetooth hardware, and starts all 434 * Bluetooth system services. 435 * <p class="caution"><strong>Bluetooth should never be enabled without 436 * direct user consent</strong>. If you want to turn on Bluetooth in order 437 * to create a wireless connection, you should use the {@link 438 * #ACTION_REQUEST_ENABLE} Intent, which will raise a dialog that requests 439 * user permission to turn on Bluetooth. The {@link #enable()} method is 440 * provided only for applications that include a user interface for changing 441 * system settings, such as a "power manager" app.</p> 442 * <p>This is an asynchronous call: it will return immediately, and 443 * clients should listen for {@link #ACTION_STATE_CHANGED} 444 * to be notified of subsequent adapter state changes. If this call returns 445 * true, then the adapter state will immediately transition from {@link 446 * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time 447 * later transition to either {@link #STATE_OFF} or {@link 448 * #STATE_ON}. If this call returns false then there was an 449 * immediate problem that will prevent the adapter from being turned on - 450 * such as Airplane mode, or the adapter is already turned on. 451 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 452 * permission 453 * 454 * @return true to indicate adapter startup has begun, or false on 455 * immediate error 456 */ 457 public boolean enable() { 458 try { 459 return mService.enable(); 460 } catch (RemoteException e) {Log.e(TAG, "", e);} 461 return false; 462 } 463 464 /** 465 * Turn off the local Bluetooth adapter—do not use without explicit 466 * user action to turn off Bluetooth. 467 * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth 468 * system services, and powers down the underlying Bluetooth hardware. 469 * <p class="caution"><strong>Bluetooth should never be disabled without 470 * direct user consent</strong>. The {@link #disable()} 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_ON} to {@link #STATE_TURNING_OFF}, 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 off - 481 * such as the adapter already being turned off. 482 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 483 * permission 484 * 485 * @return true to indicate adapter shutdown has begun, or false on 486 * immediate error 487 */ 488 public boolean disable() { 489 try { 490 return mService.disable(true); 491 } catch (RemoteException e) {Log.e(TAG, "", e);} 492 return false; 493 } 494 495 /** 496 * Returns the hardware address of the local Bluetooth adapter. 497 * <p>For example, "00:11:22:AA:BB:CC". 498 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 499 * 500 * @return Bluetooth hardware address as string 501 */ 502 public String getAddress() { 503 try { 504 return mService.getAddress(); 505 } catch (RemoteException e) {Log.e(TAG, "", e);} 506 return null; 507 } 508 509 /** 510 * Get the friendly Bluetooth name of the local Bluetooth adapter. 511 * <p>This name is visible to remote Bluetooth devices. 512 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 513 * 514 * @return the Bluetooth name, or null on error 515 */ 516 public String getName() { 517 try { 518 return mService.getName(); 519 } catch (RemoteException e) {Log.e(TAG, "", e);} 520 return null; 521 } 522 523 /** 524 * Set the friendly Bluetooth name of the local Bluetooth adapter. 525 * <p>This name is visible to remote Bluetooth devices. 526 * <p>Valid Bluetooth names are a maximum of 248 bytes using UTF-8 527 * encoding, although many remote devices can only display the first 528 * 40 characters, and some may be limited to just 20. 529 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 530 * will return false. After turning on Bluetooth, 531 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 532 * to get the updated value. 533 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} 534 * 535 * @param name a valid Bluetooth name 536 * @return true if the name was set, false otherwise 537 */ 538 public boolean setName(String name) { 539 if (getState() != STATE_ON) return false; 540 try { 541 return mService.setName(name); 542 } catch (RemoteException e) {Log.e(TAG, "", e);} 543 return false; 544 } 545 546 /** 547 * Get the current Bluetooth scan mode of the local Bluetooth adapter. 548 * <p>The Bluetooth scan mode determines if the local adapter is 549 * connectable and/or discoverable from remote Bluetooth devices. 550 * <p>Possible values are: 551 * {@link #SCAN_MODE_NONE}, 552 * {@link #SCAN_MODE_CONNECTABLE}, 553 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. 554 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 555 * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth, 556 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 557 * to get the updated value. 558 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 559 * 560 * @return scan mode 561 */ 562 public int getScanMode() { 563 if (getState() != STATE_ON) return SCAN_MODE_NONE; 564 try { 565 return mService.getScanMode(); 566 } catch (RemoteException e) {Log.e(TAG, "", e);} 567 return SCAN_MODE_NONE; 568 } 569 570 /** 571 * Set the Bluetooth scan mode of the local Bluetooth adapter. 572 * <p>The Bluetooth scan mode determines if the local adapter is 573 * connectable and/or discoverable from remote Bluetooth devices. 574 * <p>For privacy reasons, discoverable mode is automatically turned off 575 * after <code>duration</code> seconds. For example, 120 seconds should be 576 * enough for a remote device to initiate and complete its discovery 577 * process. 578 * <p>Valid scan mode values are: 579 * {@link #SCAN_MODE_NONE}, 580 * {@link #SCAN_MODE_CONNECTABLE}, 581 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. 582 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 583 * will return false. After turning on Bluetooth, 584 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 585 * to get the updated value. 586 * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS} 587 * <p>Applications cannot set the scan mode. They should use 588 * <code>startActivityForResult( 589 * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE}) 590 * </code>instead. 591 * 592 * @param mode valid scan mode 593 * @param duration time in seconds to apply scan mode, only used for 594 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE} 595 * @return true if the scan mode was set, false otherwise 596 * @hide 597 */ 598 public boolean setScanMode(int mode, int duration) { 599 if (getState() != STATE_ON) return false; 600 try { 601 return mService.setScanMode(mode, duration); 602 } catch (RemoteException e) {Log.e(TAG, "", e);} 603 return false; 604 } 605 606 /** @hide */ 607 public boolean setScanMode(int mode) { 608 if (getState() != STATE_ON) return false; 609 return setScanMode(mode, 120); 610 } 611 612 /** @hide */ 613 public int getDiscoverableTimeout() { 614 if (getState() != STATE_ON) return -1; 615 try { 616 return mService.getDiscoverableTimeout(); 617 } catch (RemoteException e) {Log.e(TAG, "", e);} 618 return -1; 619 } 620 621 /** @hide */ 622 public void setDiscoverableTimeout(int timeout) { 623 if (getState() != STATE_ON) return; 624 try { 625 mService.setDiscoverableTimeout(timeout); 626 } catch (RemoteException e) {Log.e(TAG, "", e);} 627 } 628 629 /** 630 * Start the remote device discovery process. 631 * <p>The discovery process usually involves an inquiry scan of about 12 632 * seconds, followed by a page scan of each new device to retrieve its 633 * Bluetooth name. 634 * <p>This is an asynchronous call, it will return immediately. Register 635 * for {@link #ACTION_DISCOVERY_STARTED} and {@link 636 * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the 637 * discovery starts and completes. Register for {@link 638 * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices 639 * are found. 640 * <p>Device discovery is a heavyweight procedure. New connections to 641 * remote Bluetooth devices should not be attempted while discovery is in 642 * progress, and existing connections will experience limited bandwidth 643 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 644 * discovery. Discovery is not managed by the Activity, 645 * but is run as a system service, so an application should always call 646 * {@link BluetoothAdapter#cancelDiscovery()} even if it 647 * did not directly request a discovery, just to be sure. 648 * <p>Device discovery will only find remote devices that are currently 649 * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are 650 * not discoverable by default, and need to be entered into a special mode. 651 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 652 * will return false. After turning on Bluetooth, 653 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 654 * to get the updated value. 655 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}. 656 * 657 * @return true on success, false on error 658 */ 659 public boolean startDiscovery() { 660 if (getState() != STATE_ON) return false; 661 try { 662 return mService.startDiscovery(); 663 } catch (RemoteException e) {Log.e(TAG, "", e);} 664 return false; 665 } 666 667 /** 668 * Cancel the current device discovery process. 669 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}. 670 * <p>Because discovery is a heavyweight procedure for the Bluetooth 671 * adapter, this method should always be called before attempting to connect 672 * to a remote device with {@link 673 * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by 674 * the Activity, but is run as a system service, so an application should 675 * always call cancel discovery even if it did not directly request a 676 * discovery, just to be sure. 677 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 678 * will return false. After turning on Bluetooth, 679 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 680 * to get the updated value. 681 * 682 * @return true on success, false on error 683 */ 684 public boolean cancelDiscovery() { 685 if (getState() != STATE_ON) return false; 686 try { 687 mService.cancelDiscovery(); 688 } catch (RemoteException e) {Log.e(TAG, "", e);} 689 return false; 690 } 691 692 /** 693 * Return true if the local Bluetooth adapter is currently in the device 694 * discovery process. 695 * <p>Device discovery is a heavyweight procedure. New connections to 696 * remote Bluetooth devices should not be attempted while discovery is in 697 * progress, and existing connections will experience limited bandwidth 698 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing 699 * discovery. 700 * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED} 701 * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery 702 * starts or completes. 703 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 704 * will return false. After turning on Bluetooth, 705 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 706 * to get the updated value. 707 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 708 * 709 * @return true if discovering 710 */ 711 public boolean isDiscovering() { 712 if (getState() != STATE_ON) return false; 713 try { 714 return mService.isDiscovering(); 715 } catch (RemoteException e) {Log.e(TAG, "", e);} 716 return false; 717 } 718 719 /** 720 * Return the set of {@link BluetoothDevice} objects that are bonded 721 * (paired) to the local adapter. 722 * <p>If Bluetooth state is not {@link #STATE_ON}, this API 723 * will return an empty set. After turning on Bluetooth, 724 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON} 725 * to get the updated value. 726 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}. 727 * 728 * @return unmodifiable set of {@link BluetoothDevice}, or null on error 729 */ 730 public Set<BluetoothDevice> getBondedDevices() { 731 if (getState() != STATE_ON) { 732 return toDeviceSet(new String[0]); 733 } 734 try { 735 return toDeviceSet(mService.listBonds()); 736 } catch (RemoteException e) {Log.e(TAG, "", e);} 737 return null; 738 } 739 740 /** 741 * Get the current connection state of the local Bluetooth adapter. 742 * This can be used to check whether the local Bluetooth adapter is connected 743 * to any profile of any other remote Bluetooth Device. 744 * 745 * <p> Use this function along with {@link #ACTION_CONNECTION_STATE_CHANGED} 746 * intent to get the connection state of the adapter. 747 * 748 * @return One of {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTED}, 749 * {@link #STATE_CONNECTING} or {@link #STATE_DISCONNECTED} 750 * 751 * @hide 752 */ 753 public int getConnectionState() { 754 if (getState() != STATE_ON) return BluetoothAdapter.STATE_DISCONNECTED; 755 try { 756 return mService.getAdapterConnectionState(); 757 } catch (RemoteException e) {Log.e(TAG, "getConnectionState:", e);} 758 return BluetoothAdapter.STATE_DISCONNECTED; 759 } 760 761 /** 762 * Picks RFCOMM channels until none are left. 763 * Avoids reserved channels. 764 */ 765 private static class RfcommChannelPicker { 766 private static final int[] RESERVED_RFCOMM_CHANNELS = new int[] { 767 10, // HFAG 768 11, // HSAG 769 12, // OPUSH 770 19, // PBAP 771 }; 772 private static LinkedList<Integer> sChannels; // master list of non-reserved channels 773 private static Random sRandom; 774 775 private final LinkedList<Integer> mChannels; // local list of channels left to try 776 777 private final UUID mUuid; 778 779 public RfcommChannelPicker(UUID uuid) { 780 synchronized (RfcommChannelPicker.class) { 781 if (sChannels == null) { 782 // lazy initialization of non-reserved rfcomm channels 783 sChannels = new LinkedList<Integer>(); 784 for (int i = 1; i <= BluetoothSocket.MAX_RFCOMM_CHANNEL; i++) { 785 sChannels.addLast(new Integer(i)); 786 } 787 for (int reserved : RESERVED_RFCOMM_CHANNELS) { 788 sChannels.remove(new Integer(reserved)); 789 } 790 sRandom = new Random(); 791 } 792 mChannels = (LinkedList<Integer>)sChannels.clone(); 793 } 794 mUuid = uuid; 795 } 796 /* Returns next random channel, or -1 if we're out */ 797 public int nextChannel() { 798 if (mChannels.size() == 0) { 799 return -1; 800 } 801 return mChannels.remove(sRandom.nextInt(mChannels.size())); 802 } 803 } 804 805 /** 806 * Create a listening, secure RFCOMM Bluetooth socket. 807 * <p>A remote device connecting to this socket will be authenticated and 808 * communication on this socket will be encrypted. 809 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 810 * connections from a listening {@link BluetoothServerSocket}. 811 * <p>Valid RFCOMM channels are in range 1 to 30. 812 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} 813 * @param channel RFCOMM channel to listen on 814 * @return a listening RFCOMM BluetoothServerSocket 815 * @throws IOException on error, for example Bluetooth not available, or 816 * insufficient permissions, or channel in use. 817 * @hide 818 */ 819 public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException { 820 BluetoothServerSocket socket = new BluetoothServerSocket( 821 BluetoothSocket.TYPE_RFCOMM, true, true, channel); 822 int errno = socket.mSocket.bindListen(); 823 if (errno != 0) { 824 try { 825 socket.close(); 826 } catch (IOException e) {} 827 socket.mSocket.throwErrnoNative(errno); 828 } 829 return socket; 830 } 831 832 /** 833 * Create a listening, secure RFCOMM Bluetooth socket with Service Record. 834 * <p>A remote device connecting to this socket will be authenticated and 835 * communication on this socket will be encrypted. 836 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming 837 * connections from a listening {@link BluetoothServerSocket}. 838 * <p>The system will assign an unused RFCOMM channel to listen on. 839 * <p>The system will also register a Service Discovery 840 * Protocol (SDP) record with the local SDP server containing the specified 841 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices 842 * can use the same UUID to query our SDP server and discover which channel 843 * to connect to. This SDP record will be removed when this socket is 844 * closed, or if this application closes unexpectedly. 845 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to 846 * connect to this socket from another device using the same {@link UUID}. 847 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 848 * @param name service name for SDP record 849 * @param uuid uuid for SDP record 850 * @return a listening RFCOMM BluetoothServerSocket 851 * @throws IOException on error, for example Bluetooth not available, or 852 * insufficient permissions, or channel in use. 853 */ 854 public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid) 855 throws IOException { 856 RfcommChannelPicker picker = new RfcommChannelPicker(uuid); 857 858 BluetoothServerSocket socket; 859 int channel; 860 int errno; 861 while (true) { 862 channel = picker.nextChannel(); 863 864 if (channel == -1) { 865 throw new IOException("No available channels"); 866 } 867 868 socket = new BluetoothServerSocket( 869 BluetoothSocket.TYPE_RFCOMM, true, true, channel); 870 errno = socket.mSocket.bindListen(); 871 if (errno == 0) { 872 if (DBG) Log.d(TAG, "listening on RFCOMM channel " + channel); 873 break; // success 874 } else if (errno == BluetoothSocket.EADDRINUSE) { 875 if (DBG) Log.d(TAG, "RFCOMM channel " + channel + " in use"); 876 try { 877 socket.close(); 878 } catch (IOException e) {} 879 continue; // try another channel 880 } else { 881 try { 882 socket.close(); 883 } catch (IOException e) {} 884 socket.mSocket.throwErrnoNative(errno); // Exception as a result of bindListen() 885 } 886 } 887 888 int handle = -1; 889 try { 890 handle = mService.addRfcommServiceRecord(name, new ParcelUuid(uuid), channel, 891 new Binder()); 892 } catch (RemoteException e) {Log.e(TAG, "", e);} 893 if (handle == -1) { 894 try { 895 socket.close(); 896 } catch (IOException e) {} 897 throw new IOException("Not able to register SDP record for " + name); 898 } 899 socket.setCloseHandler(mHandler, handle); 900 return socket; 901 } 902 903 904 /** 905 * Construct an unencrypted, unauthenticated, RFCOMM server socket. 906 * Call #accept to retrieve connections to this socket. 907 * @return An RFCOMM BluetoothServerSocket 908 * @throws IOException On error, for example Bluetooth not available, or 909 * insufficient permissions. 910 * @hide 911 */ 912 public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException { 913 BluetoothServerSocket socket = new BluetoothServerSocket( 914 BluetoothSocket.TYPE_RFCOMM, false, false, port); 915 int errno = socket.mSocket.bindListen(); 916 if (errno != 0) { 917 try { 918 socket.close(); 919 } catch (IOException e) {} 920 socket.mSocket.throwErrnoNative(errno); 921 } 922 return socket; 923 } 924 925 /** 926 * Construct a SCO server socket. 927 * Call #accept to retrieve connections to this socket. 928 * @return A SCO BluetoothServerSocket 929 * @throws IOException On error, for example Bluetooth not available, or 930 * insufficient permissions. 931 * @hide 932 */ 933 public static BluetoothServerSocket listenUsingScoOn() throws IOException { 934 BluetoothServerSocket socket = new BluetoothServerSocket( 935 BluetoothSocket.TYPE_SCO, false, false, -1); 936 int errno = socket.mSocket.bindListen(); 937 if (errno != 0) { 938 try { 939 socket.close(); 940 } catch (IOException e) {} 941 socket.mSocket.throwErrnoNative(errno); 942 } 943 return socket; 944 } 945 946 /** 947 * Read the local Out of Band Pairing Data 948 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} 949 * 950 * @return Pair<byte[], byte[]> of Hash and Randomizer 951 * 952 * @hide 953 */ 954 public Pair<byte[], byte[]> readOutOfBandData() { 955 if (getState() != STATE_ON) return null; 956 try { 957 byte[] hash; 958 byte[] randomizer; 959 960 byte[] ret = mService.readOutOfBandData(); 961 962 if (ret == null || ret.length != 32) return null; 963 964 hash = Arrays.copyOfRange(ret, 0, 16); 965 randomizer = Arrays.copyOfRange(ret, 16, 32); 966 967 if (DBG) { 968 Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) + 969 ":" + Arrays.toString(randomizer)); 970 } 971 return new Pair<byte[], byte[]>(hash, randomizer); 972 973 } catch (RemoteException e) {Log.e(TAG, "", e);} 974 return null; 975 } 976 977 /* 978 * Get the profile proxy object associated with the profile. 979 * 980 * <p>Profile can be one of {@link BluetoothProfile.HEADSET} or 981 * {@link BluetoothProfile.A2DP}. Clients must implements 982 * {@link BluetoothProfile.ServiceListener} to get notified of 983 * the connection status and to get the proxy object. 984 * 985 * @param context Context of the application 986 * @param listener The service Listener for connection callbacks. 987 * @param profile 988 * @return true on success, false on error 989 */ 990 public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener, 991 int profile) { 992 if (context == null || listener == null) return false; 993 994 if (profile == BluetoothProfile.HEADSET) { 995 BluetoothHeadset headset = new BluetoothHeadset(context, listener); 996 return true; 997 } else if (profile == BluetoothProfile.A2DP) { 998 BluetoothA2dp a2dp = new BluetoothA2dp(context, listener); 999 return true; 1000 } else { 1001 return false; 1002 } 1003 } 1004 1005 /** 1006 * Close the connection of the profile proxy to the Service. 1007 * 1008 * <p> Clients should call this when they are no longer using 1009 * the proxy obtained from {@link #getProfileProxy}. 1010 * Profile can be one of {@link BluetoothProfile#HEADSET} or 1011 * {@link BluetoothProfile#A2DP} 1012 * 1013 * @param profile 1014 * @param proxy Profile proxy object 1015 */ 1016 public void closeProfileProxy(int profile, BluetoothProfile proxy) { 1017 if (profile == BluetoothProfile.HEADSET) { 1018 BluetoothHeadset headset = (BluetoothHeadset)proxy; 1019 if (headset != null) { 1020 headset.close(); 1021 } 1022 } 1023 } 1024 1025 private Set<BluetoothDevice> toDeviceSet(String[] addresses) { 1026 Set<BluetoothDevice> devices = new HashSet<BluetoothDevice>(addresses.length); 1027 for (int i = 0; i < addresses.length; i++) { 1028 devices.add(getRemoteDevice(addresses[i])); 1029 } 1030 return Collections.unmodifiableSet(devices); 1031 } 1032 1033 private Handler mHandler = new Handler() { 1034 public void handleMessage(Message msg) { 1035 /* handle socket closing */ 1036 int handle = msg.what; 1037 try { 1038 if (DBG) Log.d(TAG, "Removing service record " + Integer.toHexString(handle)); 1039 mService.removeServiceRecord(handle); 1040 } catch (RemoteException e) {Log.e(TAG, "", e);} 1041 } 1042 }; 1043 1044 /** 1045 * Validate a Bluetooth address, such as "00:43:A8:23:10:F0" 1046 * <p>Alphabetic characters must be uppercase to be valid. 1047 * 1048 * @param address Bluetooth address as string 1049 * @return true if the address is valid, false otherwise 1050 */ 1051 public static boolean checkBluetoothAddress(String address) { 1052 if (address == null || address.length() != ADDRESS_LENGTH) { 1053 return false; 1054 } 1055 for (int i = 0; i < ADDRESS_LENGTH; i++) { 1056 char c = address.charAt(i); 1057 switch (i % 3) { 1058 case 0: 1059 case 1: 1060 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) { 1061 // hex character, OK 1062 break; 1063 } 1064 return false; 1065 case 2: 1066 if (c == ':') { 1067 break; // OK 1068 } 1069 return false; 1070 } 1071 } 1072 return true; 1073 } 1074} 1075