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