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