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