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