1 page.title=Bluetooth 2 @jd:body 3 4 <div id="qv-wrapper"> 5 <div id="qv"> 6 7 <h2>Quickview</h2> 8 <ul> 9 <li>Android's bluetooth APIs allow your application to perform wireless data transactions with 10 other devices</li> 11 </ul> 12 13 <h2>In this document</h2> 14 <ol> 15 <li><a href="#TheBasics">The Basics</a></li> 16 <li><a href="#Permissions">Bluetooth Permissions</a></li> 17 <li><a href="#SettingUp">Setting Up Bluetooth</a></li> 18 <li><a href="#FindingDevices">Finding Devices</a> 19 <ol> 20 <li><a href="#QueryingPairedDevices">Querying paired devices</a></li> 21 <li><a href="#DiscoveringDevices">Discovering devices</a></li> 22 </ol></li> 23 <li><a href="#ConnectingDevices">Connecting Devices</a> 24 <ol> 25 <li><a href="#ConnectingAsAServer">Connecting as a server</a></li> 26 <li><a href="#ConnectingAsAClient">Connecting as a client</a></li> 27 </ol></li> 28 <li><a href="#ManagingAConnection">Managing a Connection</a></li> 29 <li><a href="#Profiles">Working with Profiles</a> 30 <ol> 31 <li><a href="#AT-Commands">Vendor-specific AT commands</a> 32 </ol></li> 33 </ol> 34 35 <h2>Key classes</h2> 36 <ol> 37 <li>{@link android.bluetooth.BluetoothAdapter}</li> 38 <li>{@link android.bluetooth.BluetoothDevice}</li> 39 <li>{@link android.bluetooth.BluetoothSocket}</li> 40 <li>{@link android.bluetooth.BluetoothServerSocket}</li> 41 </ol> 42 43 <h2>Related samples</h2> 44 <ol> 45 <li><a href="{@docRoot}resources/samples/BluetoothChat/index.html">Bluetooth Chat</a></li> 46 </ol> 47 48 </div> 49 </div> 50 51 52 <p>The Android platform includes support for the Bluetooth network stack, 53 which allows a device to wirelessly exchange data with other Bluetooth devices. 54 The application framework provides access to the Bluetooth functionality through 55 the Android Bluetooth APIs. These APIs let applications wirelessly 56 connect to other Bluetooth devices, enabling point-to-point and multipoint 57 wireless features.</p> 58 59 <p>Using the Bluetooth APIs, an Android application can perform the 60 following:</p> 61 <ul> 62 <li>Scan for other Bluetooth devices</li> 63 <li>Query the local Bluetooth adapter for paired Bluetooth devices</li> 64 <li>Establish RFCOMM channels</li> 65 <li>Connect to other devices through service discovery</li> 66 <li>Transfer data to and from other devices</li> 67 <li>Manage multiple connections</li> 68 </ul> 69 70 71 <h2 id="TheBasics">The Basics</h2> 72 73 <p>This document describes how to use the Android Bluetooth APIs to accomplish 74 the four major tasks necessary to communicate using Bluetooth: setting up 75 Bluetooth, finding devices that are either paired or available in the local 76 area, connecting devices, and transferring data between devices.</p> 77 78 <p>All of the Bluetooth APIs are available in the {@link android.bluetooth} 79 package. Here's a summary of the classes and interfaces you will need to create Bluetooth 80 connections:</p> 81 82 <dl> 83 <dt>{@link android.bluetooth.BluetoothAdapter}</dt> 84 <dd>Represents the local Bluetooth adapter (Bluetooth radio). The 85 {@link android.bluetooth.BluetoothAdapter} is the entry-point for all Bluetooth 86 interaction. Using this, 87 you can discover other Bluetooth devices, query a list of bonded (paired) 88 devices, instantiate a {@link android.bluetooth.BluetoothDevice} using a known 89 MAC address, and create a {@link android.bluetooth.BluetoothServerSocket} to 90 listen for communications 91 from other devices.</dd> 92 93 <dt>{@link android.bluetooth.BluetoothDevice}</dt> 94 <dd>Represents a remote Bluetooth device. Use this to request a connection 95 with a remote device through a {@link android.bluetooth.BluetoothSocket} or 96 query information about the 97 device such as its name, address, class, and bonding state.</dd> 98 99 <dt>{@link android.bluetooth.BluetoothSocket}</dt> 100 <dd>Represents the interface for a Bluetooth socket (similar to a TCP 101 {@link java.net.Socket}). This is the connection point that allows 102 an application to exchange data with another Bluetooth device via InputStream 103 and OutputStream.</dd> 104 105 <dt>{@link android.bluetooth.BluetoothServerSocket}</dt> 106 <dd>Represents an open server socket that listens for incoming requests 107 (similar to a TCP {@link java.net.ServerSocket}). In order to connect two 108 Android devices, one device must open a server socket with this class. When a 109 remote Bluetooth device makes a connection request to the this device, the 110 {@link android.bluetooth.BluetoothServerSocket} will return a connected {@link 111 android.bluetooth.BluetoothSocket} when the 112 connection is accepted.</dd> 113 114 <dt>{@link android.bluetooth.BluetoothClass}</dt> 115 <dd>Describes the general characteristics and capabilities of a Bluetooth 116 device. This is a read-only set of properties that define the device's major and 117 minor device classes and its services. However, this does not reliably describe 118 all Bluetooth profiles and services supported by the device, but is useful as a 119 hint to the device type.</dd> 120 121 <dt>{@link android.bluetooth.BluetoothProfile}</dt> <dd>An interface that 122 represents a Bluetooth profile. A <em>Bluetooth profile</em> is a wireless 123 interface specification for Bluetooth-based communication between devices. An 124 example is the Hands-Free profile. For more discussion of profiles, see <a 125 href="#Profiles">Working with Profiles</a></dd> 126 127 <dt>{@link android.bluetooth.BluetoothHeadset}</dt> <dd>Provides support for 128 Bluetooth headsets to be used with mobile phones. This includes both Bluetooth 129 Headset and Hands-Free (v1.5) profiles.</dd> 130 131 <dt>{@link android.bluetooth.BluetoothA2dp}</dt> <dd> Defines how high quality 132 audio can be streamed from one device to another over a Bluetooth connection. 133 "A2DP" stands for Advanced Audio Distribution Profile.</dd> 134 135 <dt>{@link android.bluetooth.BluetoothProfile.ServiceListener}</dt> 136 137 <dd>An interface that notifies {@link android.bluetooth.BluetoothProfile} IPC 138 clients when they have been connected to or disconnected from the service (that 139 is, the internal service that runs a particular profile). </dd> 140 141 </dl> 142 143 144 145 146 <h2 id="Permissions">Bluetooth Permissions</h2> 147 148 <p>In order to use Bluetooth features in your application, you need to declare 149 at least one of two Bluetooth permissions: {@link 150 android.Manifest.permission#BLUETOOTH} and {@link 151 android.Manifest.permission#BLUETOOTH_ADMIN}.</p> 152 153 <p>You must request the {@link android.Manifest.permission#BLUETOOTH} permission 154 in order to perform any Bluetooth communication, such as requesting a 155 connection, accepting a connection, and transferring data.</p> 156 157 <p>You must request the {@link android.Manifest.permission#BLUETOOTH_ADMIN} 158 permission in order to initiate device discovery or manipulate Bluetooth 159 settings. Most applications need this permission solely for the 160 ability to discover local Bluetooth devices. The other abilities granted by this 161 permission should not be used, unless the application is a "power manager" that 162 will modify Bluetooth settings upon user request. <strong>Note:</strong> If you 163 use {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission, then must 164 also have the {@link android.Manifest.permission#BLUETOOTH} permission.</p> 165 166 <p>Declare the Bluetooth permission(s) in your application manifest file. For 167 example:</p> 168 169 <pre> 170 <manifest ... > 171 <uses-permission android:name="android.permission.BLUETOOTH" /> 172 ... 173 </manifest> 174 </pre> 175 176 <p>See the <a 177 href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><uses-permission></a> 178 reference for more information about declaring application permissions.</p> 179 180 181 <h2 id="SettingUp">Setting Up Bluetooth</h2> 182 183 <div class="figure" style="width:200px"> 184 <img src="{@docRoot}images/bt_enable_request.png" /> 185 <strong>Figure 1:</strong> The enabling Bluetooth dialog. 186 </div> 187 188 <p>Before your application can communicate over Bluetooth, you need to verify 189 that Bluetooth is supported on the device, and if so, ensure that it is enabled.</p> 190 191 <p>If Bluetooth is not supported, then you should gracefully disable any 192 Bluetooth features. If Bluetooth is supported, but disabled, then you can request that the 193 user enable Bluetooth without leaving your application. This setup is 194 accomplished in two steps, using the {@link android.bluetooth.BluetoothAdapter}.</p> 195 196 197 <ol> 198 <li>Get the {@link android.bluetooth.BluetoothAdapter} 199 <p>The {@link android.bluetooth.BluetoothAdapter} is required for any and all Bluetooth 200 activity. To get the {@link android.bluetooth.BluetoothAdapter}, call the static {@link 201 android.bluetooth.BluetoothAdapter#getDefaultAdapter()} method. This returns a 202 {@link android.bluetooth.BluetoothAdapter} that represents the device's own 203 Bluetooth adapter (the Bluetooth radio). There's one Bluetooth adapter for the 204 entire system, and your application can interact with it using this object. If 205 {@link android.bluetooth.BluetoothAdapter#getDefaultAdapter()} returns null, 206 then the device does not support Bluetooth and your story ends here. For example:</p> 207 <pre> 208 BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 209 if (mBluetoothAdapter == null) { 210 // Device does not support Bluetooth 211 } 212 </pre> 213 </li> 214 215 <li>Enable Bluetooth 216 <p>Next, you need to ensure that Bluetooth is enabled. Call {@link 217 android.bluetooth.BluetoothAdapter#isEnabled()} to check whether Bluetooth is 218 currently enable. If this method returns false, then Bluetooth is disabled. To 219 request that Bluetooth be enabled, call {@link 220 android.app.Activity#startActivityForResult(Intent,int) startActivityForResult()} 221 with the {@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_ENABLE} action Intent. 222 This will issue a request to enable Bluetooth through the system settings (without 223 stopping your application). For example:</p> 224 <pre> 225 if (!mBluetoothAdapter.isEnabled()) { 226 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 227 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 228 } 229 </pre> 230 231 <p>A dialog will appear requesting user permission to enable Bluetooth, as shown 232 in Figure 1. If the user responds "Yes," the system will begin to enable Bluetooth 233 and focus will return to your application once the process completes (or fails).</p> 234 <p>If enabling Bluetooth succeeds, your Activity will receive the {@link 235 android.app.Activity#RESULT_OK} result code in the {@link 236 android.app.Activity#onActivityResult(int,int,Intent) onActivityResult()} 237 callback. If Bluetooth was not enabled 238 due to an error (or the user responded "No") then the result code will be {@link 239 android.app.Activity#RESULT_CANCELED}.</p> 240 </li> 241 </ol> 242 243 <p>Optionally, your application can also listen for the 244 {@link android.bluetooth.BluetoothAdapter#ACTION_STATE_CHANGED} broadcast Intent, which 245 the system will broadcast whenever the Bluetooth state has changed. This broadcast contains 246 the extra fields {@link android.bluetooth.BluetoothAdapter#EXTRA_STATE} and {@link 247 android.bluetooth.BluetoothAdapter#EXTRA_PREVIOUS_STATE}, containing the new and old 248 Bluetooth states, respectively. Possible values for these extra fields are 249 {@link android.bluetooth.BluetoothAdapter#STATE_TURNING_ON}, {@link 250 android.bluetooth.BluetoothAdapter#STATE_ON}, {@link 251 android.bluetooth.BluetoothAdapter#STATE_TURNING_OFF}, and {@link 252 android.bluetooth.BluetoothAdapter#STATE_OFF}. Listening for this 253 broadcast can be useful to detect changes made to the Bluetooth state while your 254 app is running.</p> 255 256 <p class="note"><strong>Tip:</strong> Enabling discoverability will automatically 257 enable Bluetooth. If you plan to consistently enable device discoverability before 258 performing Bluetooth activity, you can skip 259 step 2 above. Read about <a href="#EnablingDiscoverability">enabling discoverability</a>, 260 below.</p> 261 262 263 <h2 id="FindingDevices">Finding Devices</h2> 264 265 <p>Using the {@link android.bluetooth.BluetoothAdapter}, you can find remote Bluetooth 266 devices either through device discovery or by querying the list of paired (bonded) 267 devices.</p> 268 269 <p>Device discovery is a scanning procedure that searches the local area for 270 Bluetooth enabled devices and then requesting some information about each one 271 (this is sometimes referred to as "discovering," "inquiring" or "scanning"). 272 However, a Bluetooth device within the local area will respond to a discovery 273 request only if it is currently enabled to be discoverable. If a device is 274 discoverable, it will respond to the discovery request by sharing some 275 information, such as the device name, class, and its unique MAC address. Using 276 this information, the device performing discovery can then choose to initiate a 277 connection to the discovered device.</p> 278 279 <p>Once a connection is made with a remote device for the first time, a pairing 280 request is automatically presented to the user. When a device is 281 paired, the basic information about that device (such as the device name, class, 282 and MAC address) is saved and can be read using the Bluetooth APIs. Using the 283 known MAC address for a remote device, a connection can be initiated with it at 284 any time without performing discovery (assuming the device is within range).</p> 285 286 <p>Remember there is a difference between being paired and being connected. To 287 be paired means that two devices are aware of each other's existence, have a 288 shared link-key that can be used for authentication, and are capable of 289 establishing an encrypted connection with each other. To be connected means that 290 the devices currently share an RFCOMM channel and are able to transmit data with 291 each other. The current Android Bluetooth API's require devices to be paired 292 before an RFCOMM connection can be established. (Pairing is automatically performed 293 when you initiate an encrypted connection with the Bluetooth APIs.)</p> 294 295 <p>The following sections describe how to find devices that have been paired, or 296 discover new devices using device discovery.</p> 297 298 <p class="note"><strong>Note:</strong> Android-powered devices are not 299 discoverable by default. A user can make 300 the device discoverable for a limited time through the system settings, or an 301 application can request that the user enable discoverability without leaving the 302 application. How to <a href="#EnablingDiscoverability">enable discoverability</a> 303 is discussed below.</p> 304 305 306 <h3 id="QueryingPairedDevices">Querying paired devices</h3> 307 308 <p>Before performing device discovery, its worth querying the set 309 of paired devices to see if the desired device is already known. To do so, 310 call {@link android.bluetooth.BluetoothAdapter#getBondedDevices()}. This 311 will return a Set of {@link android.bluetooth.BluetoothDevice}s representing 312 paired devices. For example, you can query all paired devices and then 313 show the name of each device to the user, using an ArrayAdapter:</p> 314 <pre> 315 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 316 // If there are paired devices 317 if (pairedDevices.size() > 0) { 318 // Loop through paired devices 319 for (BluetoothDevice device : pairedDevices) { 320 // Add the name and address to an array adapter to show in a ListView 321 mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 322 } 323 } 324 </pre> 325 326 <p>All that's needed from the {@link android.bluetooth.BluetoothDevice} object 327 in order to initiate a connection is the MAC address. In this example, it's saved 328 as a part of an ArrayAdapter that's shown to the user. The MAC address can later 329 be extracted in order to initiate the connection. You can learn more about creating 330 a connection in the section about <a href="#ConnectingDevices">Connecting Devices</a>.</p> 331 332 333 <h3 id="DiscoveringDevices">Discovering devices</h3> 334 335 <p>To start discovering devices, simply call {@link 336 android.bluetooth.BluetoothAdapter#startDiscovery()}. The 337 process is asynchronous and the method will immediately return with a boolean 338 indicating whether discovery has successfully started. The discovery process 339 usually involves an inquiry scan of about 12 seconds, followed by a page scan of 340 each found device to retrieve its Bluetooth name.</p> 341 342 <p>Your application must register a BroadcastReceiver for the 343 {@link android.bluetooth.BluetoothDevice#ACTION_FOUND} Intent in 344 order to receive information about each 345 device discovered. For each device, the system will broadcast the 346 {@link android.bluetooth.BluetoothDevice#ACTION_FOUND} Intent. This 347 Intent carries the extra fields 348 {@link android.bluetooth.BluetoothDevice#EXTRA_DEVICE} and 349 {@link android.bluetooth.BluetoothDevice#EXTRA_CLASS}, containing a 350 {@link android.bluetooth.BluetoothDevice} and a {@link 351 android.bluetooth.BluetoothClass}, respectively. For example, here's how you can 352 register to handle the broadcast when devices are discovered:</p> 353 <pre> 354 // Create a BroadcastReceiver for ACTION_FOUND 355 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 356 public void onReceive(Context context, Intent intent) { 357 String action = intent.getAction(); 358 // When discovery finds a device 359 if (BluetoothDevice.ACTION_FOUND.equals(action)) { 360 // Get the BluetoothDevice object from the Intent 361 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 362 // Add the name and address to an array adapter to show in a ListView 363 mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 364 } 365 } 366 }; 367 // Register the BroadcastReceiver 368 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 369 registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy 370 </pre> 371 372 <p>All that's needed from the {@link android.bluetooth.BluetoothDevice} object 373 in order to initiate a 374 connection is the MAC address. In this example, it's saved as a part of an 375 ArrayAdapter that's shown to the user. The MAC address can later be extracted in 376 order to initiate the connection. You can learn more about creating a connection 377 in the section about <a href="#ConnectingDevices">Connecting Devices</a>.</p> 378 379 <p class="caution"><strong>Caution:</strong> Performing device discovery is 380 a heavy procedure for the Bluetooth 381 adapter and will consume a lot of its resources. Once you have found a device to 382 connect, be certain that you always stop discovery with 383 {@link android.bluetooth.BluetoothAdapter#cancelDiscovery()} before 384 attempting a connection. Also, if you 385 already hold a connection with a device, then performing discovery can 386 significantly reduce the bandwidth available for the connection, so you should 387 not perform discovery while connected.</p> 388 389 <h4 id="EnablingDiscoverability">Enabling discoverability</h4> 390 391 <p>If you would like to make the local device discoverable to other devices, 392 call {@link android.app.Activity#startActivityForResult(Intent,int)} with the 393 {@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_DISCOVERABLE} action 394 Intent. This will issue a request to enable discoverable mode through the system 395 settings (without stopping your application). By default, the device will become 396 discoverable for 120 seconds. You can define a different duration by adding the 397 {@link android.bluetooth.BluetoothAdapter#EXTRA_DISCOVERABLE_DURATION} Intent 398 extra. The maximum duration an app can set is 3600 seconds, and a value of 0 399 means the device is always discoverable. Any value below 0 or above 3600 is 400 automatically set to 120 secs). For example, this snippet sets the duration to 401 300:</p> 402 403 <pre>Intent discoverableIntent = new 404 Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 405 discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); 406 startActivity(discoverableIntent); 407 </pre> 408 409 <div class="figure" style="width:200px"> 410 <img src="{@docRoot}images/bt_enable_discoverable.png" /> 411 <strong>Figure 2:</strong> The enabling discoverability dialog. 412 </div> 413 414 <p>A dialog will be displayed, requesting user permission to make the device 415 discoverable, as shown in Figure 2. If the user responds "Yes," then the device 416 will become discoverable for the specified amount of time. Your Activity will 417 then receive a call to the {@link android.app.Activity#onActivityResult(int,int,Intent) 418 onActivityResult())} callback, with the result code equal to the duration that the device 419 is discoverable. If the user responded "No" or if an error occurred, the result code will 420 be Activity.RESULT_CANCELLED.</p> 421 422 <p class="note"><strong>Note:</strong> If Bluetooth has not been enabled on the device, 423 then enabling device discoverability will automatically enable Bluetooth.</p> 424 425 <p>The device will silently remain in discoverable mode for the allotted time. 426 If you would like to be notified when the discoverable mode has changed, you can 427 register a BroadcastReceiver for the {@link 428 android.bluetooth.BluetoothAdapter#ACTION_SCAN_MODE_CHANGED} 429 Intent. This will contain the extra fields {@link 430 android.bluetooth.BluetoothAdapter#EXTRA_SCAN_MODE} and 431 {@link android.bluetooth.BluetoothAdapter#EXTRA_PREVIOUS_SCAN_MODE}, which tell you the 432 new and old scan mode, respectively. Possible values for each are 433 {@link android.bluetooth.BluetoothAdapter#SCAN_MODE_CONNECTABLE_DISCOVERABLE}, 434 {@link android.bluetooth.BluetoothAdapter#SCAN_MODE_CONNECTABLE}, or {@link 435 android.bluetooth.BluetoothAdapter#SCAN_MODE_NONE}, 436 which indicate that the device is either in discoverable mode, not in 437 discoverable mode but still able to receive connections, or not in discoverable 438 mode and unable to receive connections, respectively.</p> 439 440 <p>You do not need to enable device discoverability if you will be initiating 441 the connection to a remote device. Enabling discoverability is only necessary when 442 you want your application to host a server socket that will accept incoming 443 connections, because the remote devices must be able to discover the device 444 before it can initiate the connection.</p> 445 446 447 448 <h2 id="ConnectingDevices">Connecting Devices</h2> 449 450 <p>In order to create a connection between your application on two devices, you 451 must implement both the server-side and client-side mechanisms, because one 452 device must open a server socket and the other one must initiate the connection 453 (using the server device's MAC address to initiate a connection). The server and 454 client are considered connected to each other when they each have a connected 455 {@link android.bluetooth.BluetoothSocket} on the same RFCOMM channel. At this 456 point, each device can obtain input and output streams and data transfer can 457 begin, which is discussed in the section about <a 458 href="#ManagingAConnection">Managing a Connection</a>. This section describes how 459 to initiate the connection between two devices.</p> 460 461 <p>The server device and the client device each obtain the required {@link 462 android.bluetooth.BluetoothSocket} in different ways. The server will receive it 463 when an incoming connection is accepted. The client will receive it when it 464 opens an RFCOMM channel to the server.</p> 465 466 <div class="figure" style="width:200px"> 467 <img src="{@docRoot}images/bt_pairing_request.png" /> 468 <strong>Figure 3:</strong> The Bluetooth pairing dialog. 469 </div> 470 471 <p>One implementation technique is to automatically prepare each device as a 472 server, so that each one has a server socket open and listening for connections. 473 Then either device can initiate a connection with the other and become the 474 client. Alternatively, one device can explicitly "host" the connection and open 475 a server socket on demand and the other device can simply initiate the 476 connection.</p> 477 478 <p class="note"><strong>Note:</strong> If the two devices have not been previously paired, 479 then the Android framework will automatically show a pairing request notification or 480 dialog to the user during the connection procedure, as shown in Figure 3. So 481 when attempting to connect devices, 482 your application does not need to be concerned about whether or not the devices are 483 paired. Your RFCOMM connection attempt will block until the user has successfully paired, 484 or will fail if the user rejects pairing, or if pairing fails or times out. </p> 485 486 487 <h3 id="ConnectingAsAServer">Connecting as a server</h3> 488 489 <p>When you want to connect two devices, one must act as a server by holding an 490 open {@link android.bluetooth.BluetoothServerSocket}. The purpose of the server 491 socket is to listen for incoming connection requests and when one is accepted, 492 provide a connected {@link android.bluetooth.BluetoothSocket}. When the {@link 493 android.bluetooth.BluetoothSocket} is acquired from the {@link 494 android.bluetooth.BluetoothServerSocket}, 495 the {@link android.bluetooth.BluetoothServerSocket} can (and should) be 496 discarded, unless you want to accept more connections.</p> 497 498 <div class="sidebox-wrapper"> 499 <div class="sidebox"> 500 <h2>About UUID</h2> 501 502 <p>A Universally Unique Identifier (UUID) is a standardized 128-bit format for a string 503 ID used to uniquely identify information. The point of a UUID is that it's big 504 enough that you can select any random and it won't clash. In this case, it's 505 used to uniquely identify your application's Bluetooth service. To get a UUID to 506 use with your application, you can use one of the many random UUID generators on 507 the web, then initialize a {@link java.util.UUID} with {@link 508 java.util.UUID#fromString(String)}.</p> 509 </div> 510 </div> 511 512 <p>Here's the basic procedure to set up a server socket and accept a 513 connection:</p> 514 515 <ol> 516 <li>Get a {@link android.bluetooth.BluetoothServerSocket} by calling the 517 {@link 518 android.bluetooth.BluetoothAdapter#listenUsingRfcommWithServiceRecord(String, 519 UUID)}. 520 <p>The string is an identifiable name of your service, which the system will 521 automatically write to a new Service Discovery Protocol (SDP) database entry on 522 the device (the name is arbitrary and can simply be your application name). The 523 UUID is also included in the SDP entry and will be the basis for the connection 524 agreement with the client device. That is, when the client attempts to connect 525 with this device, it will carry a UUID that uniquely identifies the service with 526 which it wants to connect. These UUIDs must match in order for the connection to 527 be accepted (in the next step).</p> 528 </li> 529 530 <li>Start listening for connection requests by calling 531 {@link android.bluetooth.BluetoothServerSocket#accept()}. 532 <p>This is a blocking call. It will return when either a connection has been 533 accepted or an exception has occurred. A connection is accepted only when a 534 remote device has sent a connection request with a UUID matching the one 535 registered with this listening server socket. When successful, {@link 536 android.bluetooth.BluetoothServerSocket#accept()} will 537 return a connected {@link android.bluetooth.BluetoothSocket}.</p> 538 </li> 539 540 <li>Unless you want to accept additional connections, call 541 {@link android.bluetooth.BluetoothServerSocket#close()}. 542 <p>This releases the server socket and all its resources, but does <em>not</em> close the 543 connected {@link android.bluetooth.BluetoothSocket} that's been returned by {@link 544 android.bluetooth.BluetoothServerSocket#accept()}. Unlike TCP/IP, RFCOMM only allows one 545 connected client per channel at a time, so in most cases it makes sense to call {@link 546 android.bluetooth.BluetoothServerSocket#close()} on the {@link 547 android.bluetooth.BluetoothServerSocket} immediately after accepting a connected 548 socket.</p> 549 </li> 550 </ol> 551 552 <p>The {@link android.bluetooth.BluetoothServerSocket#accept()} call should not 553 be executed in the main Activity UI thread because it is a blocking call and 554 will prevent any other interaction with the application. It usually makes 555 sense to do all work with a {@link android.bluetooth.BluetoothServerSocket} or {@link 556 android.bluetooth.BluetoothSocket} in a new 557 thread managed by your application. To abort a blocked call such as {@link 558 android.bluetooth.BluetoothServerSocket#accept()}, call {@link 559 android.bluetooth.BluetoothServerSocket#close()} on the {@link 560 android.bluetooth.BluetoothServerSocket} (or {@link 561 android.bluetooth.BluetoothSocket}) from another thread and the blocked call will 562 immediately return. Note that all methods on a {@link 563 android.bluetooth.BluetoothServerSocket} or {@link android.bluetooth.BluetoothSocket} 564 are thread-safe.</p> 565 566 <h4>Example</h4> 567 568 <p>Here's a simplified thread for the server component that accepts incoming 569 connections:</p> 570 <pre> 571 private class AcceptThread extends Thread { 572 private final BluetoothServerSocket mmServerSocket; 573 574 public AcceptThread() { 575 // Use a temporary object that is later assigned to mmServerSocket, 576 // because mmServerSocket is final 577 BluetoothServerSocket tmp = null; 578 try { 579 // MY_UUID is the app's UUID string, also used by the client code 580 tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID); 581 } catch (IOException e) { } 582 mmServerSocket = tmp; 583 } 584 585 public void run() { 586 BluetoothSocket socket = null; 587 // Keep listening until exception occurs or a socket is returned 588 while (true) { 589 try { 590 socket = mmServerSocket.accept(); 591 } catch (IOException e) { 592 break; 593 } 594 // If a connection was accepted 595 if (socket != null) { 596 // Do work to manage the connection (in a separate thread) 597 manageConnectedSocket(socket); 598 mmServerSocket.close(); 599 break; 600 } 601 } 602 } 603 604 /** Will cancel the listening socket, and cause the thread to finish */ 605 public void cancel() { 606 try { 607 mmServerSocket.close(); 608 } catch (IOException e) { } 609 } 610 } 611 </pre> 612 613 <p>In this example, only one incoming connection is desired, so as soon as a 614 connection is accepted and the {@link android.bluetooth.BluetoothSocket} is 615 acquired, the application 616 sends the acquired {@link android.bluetooth.BluetoothSocket} to a separate 617 thread, closes the 618 {@link android.bluetooth.BluetoothServerSocket} and breaks the loop.</p> 619 620 <p>Note that when {@link android.bluetooth.BluetoothServerSocket#accept()} 621 returns the {@link android.bluetooth.BluetoothSocket}, the socket is already 622 connected, so you should <em>not</em> call {@link 623 android.bluetooth.BluetoothSocket#connect()} (as you do from the 624 client-side).</p> 625 626 <p><code>manageConnectedSocket()</code> is a fictional method in the application 627 that will 628 initiate the thread for transferring data, which is discussed in the section 629 about <a href="#ManagingAConnection">Managing a Connection</a>.</p> 630 631 <p>You should usually close your {@link android.bluetooth.BluetoothServerSocket} 632 as soon as you are done listening for incoming connections. In this example, {@link 633 android.bluetooth.BluetoothServerSocket#close()} is called as soon 634 as the {@link android.bluetooth.BluetoothSocket} is acquired. You may also want 635 to provide a public method in your thread that can close the private {@link 636 android.bluetooth.BluetoothSocket} in the event that you need to stop listening on the 637 server socket.</p> 638 639 640 <h3 id="ConnectingAsAClient">Connecting as a client</h3> 641 642 <p>In order to initiate a connection with a remote device (a device holding an 643 open 644 server socket), you must first obtain a {@link 645 android.bluetooth.BluetoothDevice} object that represents the remote device. 646 (Getting a {@link android.bluetooth.BluetoothDevice} is covered in the above 647 section about <a 648 href="#FindingDevices">Finding Devices</a>.) You must then use the 649 {@link android.bluetooth.BluetoothDevice} to acquire a {@link 650 android.bluetooth.BluetoothSocket} and initiate the connection.</p> 651 652 <p>Here's the basic procedure:</p> 653 654 <ol> 655 <li>Using the {@link android.bluetooth.BluetoothDevice}, get a {@link 656 android.bluetooth.BluetoothSocket} by calling {@link 657 android.bluetooth.BluetoothDevice#createRfcommSocketToServiceRecord(UUID)}. 658 <p>This initializes a {@link android.bluetooth.BluetoothSocket} that will 659 connect to the {@link android.bluetooth.BluetoothDevice}. The UUID passed here 660 must match the UUID used by the server device when it opened its 661 {@link android.bluetooth.BluetoothServerSocket} (with {@link 662 android.bluetooth.BluetoothAdapter#listenUsingRfcommWithServiceRecord(String, 663 UUID)}). Using the same UUID is simply a matter of hard-coding the UUID string 664 into your application and then referencing it from both the server and client 665 code.</p> 666 </li> 667 668 <li>Initiate the connection by calling {@link 669 android.bluetooth.BluetoothSocket#connect()}. 670 <p>Upon this call, the system will perform an SDP lookup on the remote device in 671 order to match the UUID. If the lookup is successful and the remote device 672 accepts the connection, it will share the RFCOMM channel to use during the 673 connection and {@link 674 android.bluetooth.BluetoothSocket#connect()} will return. This method is a 675 blocking call. If, for 676 any reason, the connection fails or the {@link 677 android.bluetooth.BluetoothSocket#connect()} method times out (after about 678 12 seconds), then it will throw an exception.</p> 679 <p>Because {@link 680 android.bluetooth.BluetoothSocket#connect()} is a blocking call, this connection 681 procedure should always be performed in a thread separate from the main Activity 682 thread.</p> 683 <p class="note">Note: You should always ensure that the device is not performing 684 device discovery when you call {@link 685 android.bluetooth.BluetoothSocket#connect()}. If discovery is in progress, then 686 the 687 connection attempt will be significantly slowed and is more likely to fail.</p> 688 </li> 689 </ol> 690 691 <h4>Example</h4> 692 693 <p>Here is a basic example of a thread that initiates a Bluetooth 694 connection:</p> 695 <pre> 696 private class ConnectThread extends Thread { 697 private final BluetoothSocket mmSocket; 698 private final BluetoothDevice mmDevice; 699 700 public ConnectThread(BluetoothDevice device) { 701 // Use a temporary object that is later assigned to mmSocket, 702 // because mmSocket is final 703 BluetoothSocket tmp = null; 704 mmDevice = device; 705 706 // Get a BluetoothSocket to connect with the given BluetoothDevice 707 try { 708 // MY_UUID is the app's UUID string, also used by the server code 709 tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 710 } catch (IOException e) { } 711 mmSocket = tmp; 712 } 713 714 public void run() { 715 // Cancel discovery because it will slow down the connection 716 mBluetoothAdapter.cancelDiscovery(); 717 718 try { 719 // Connect the device through the socket. This will block 720 // until it succeeds or throws an exception 721 mmSocket.connect(); 722 } catch (IOException connectException) { 723 // Unable to connect; close the socket and get out 724 try { 725 mmSocket.close(); 726 } catch (IOException closeException) { } 727 return; 728 } 729 730 // Do work to manage the connection (in a separate thread) 731 manageConnectedSocket(mmSocket); 732 } 733 734 /** Will cancel an in-progress connection, and close the socket */ 735 public void cancel() { 736 try { 737 mmSocket.close(); 738 } catch (IOException e) { } 739 } 740 } 741 </pre> 742 743 <p>Notice that {@link android.bluetooth.BluetoothAdapter#cancelDiscovery()} is called 744 before the connection is made. You should always do this before connecting and it is safe 745 to call without actually checking whether it is running or not (but if you do want to 746 check, call {@link android.bluetooth.BluetoothAdapter#isDiscovering()}).</p> 747 748 <p><code>manageConnectedSocket()</code> is a fictional method in the application 749 that will initiate the thread for transferring data, which is discussed in the section 750 about <a href="#ManagingAConnection">Managing a Connection</a>.</p> 751 752 <p>When you're done with your {@link android.bluetooth.BluetoothSocket}, always 753 call {@link android.bluetooth.BluetoothSocket#close()} to clean up. 754 Doing so will immediately close the connected socket and clean up all internal 755 resources.</p> 756 757 758 <h2 id="ManagingAConnection">Managing a Connection</h2> 759 760 <p>When you have successfully connected two (or more) devices, each one will 761 have a connected {@link android.bluetooth.BluetoothSocket}. This is where the fun 762 begins because you can share data between devices. Using the {@link 763 android.bluetooth.BluetoothSocket}, the general procedure to transfer arbitrary data is 764 simple:</p> 765 <ol> 766 <li>Get the {@link java.io.InputStream} and {@link java.io.OutputStream} that 767 handle transmissions through the socket, via {@link 768 android.bluetooth.BluetoothSocket#getInputStream()} and 769 {@link android.bluetooth.BluetoothSocket#getOutputStream}, respectively.</li> 770 771 <li>Read and write data to the streams with {@link 772 java.io.InputStream#read(byte[])} and {@link java.io.OutputStream#write(byte[])}.</li> 773 </ol> 774 775 <p>That's it.</p> 776 777 <p>There are, of course, implementation details to consider. First and foremost, 778 you should use a dedicated thread for all stream reading and writing. This is 779 important because both {@link java.io.InputStream#read(byte[])} and {@link 780 java.io.OutputStream#write(byte[])} methods are blocking calls. {@link 781 java.io.InputStream#read(byte[])} will block until there is something to read 782 from the stream. {@link java.io.OutputStream#write(byte[])} does not usually 783 block, but can block for flow control if the remote device is not calling {@link 784 java.io.InputStream#read(byte[])} quickly enough and the intermediate buffers are full. 785 So, your main loop in the thread should be dedicated to reading from the {@link 786 java.io.InputStream}. A separate public method in the thread can be used to initiate 787 writes to the {@link java.io.OutputStream}.</p> 788 789 <h4>Example</h4> 790 791 <p>Here's an example of how this might look:</p> 792 <pre> 793 private class ConnectedThread extends Thread { 794 private final BluetoothSocket mmSocket; 795 private final InputStream mmInStream; 796 private final OutputStream mmOutStream; 797 798 public ConnectedThread(BluetoothSocket socket) { 799 mmSocket = socket; 800 InputStream tmpIn = null; 801 OutputStream tmpOut = null; 802 803 // Get the input and output streams, using temp objects because 804 // member streams are final 805 try { 806 tmpIn = socket.getInputStream(); 807 tmpOut = socket.getOutputStream(); 808 } catch (IOException e) { } 809 810 mmInStream = tmpIn; 811 mmOutStream = tmpOut; 812 } 813 814 public void run() { 815 byte[] buffer = new byte[1024]; // buffer store for the stream 816 int bytes; // bytes returned from read() 817 818 // Keep listening to the InputStream until an exception occurs 819 while (true) { 820 try { 821 // Read from the InputStream 822 bytes = mmInStream.read(buffer); 823 // Send the obtained bytes to the UI Activity 824 mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 825 .sendToTarget(); 826 } catch (IOException e) { 827 break; 828 } 829 } 830 } 831 832 /* Call this from the main Activity to send data to the remote device */ 833 public void write(byte[] bytes) { 834 try { 835 mmOutStream.write(bytes); 836 } catch (IOException e) { } 837 } 838 839 /* Call this from the main Activity to shutdown the connection */ 840 public void cancel() { 841 try { 842 mmSocket.close(); 843 } catch (IOException e) { } 844 } 845 } 846 </pre> 847 848 <p>The constructor acquires the necessary streams and once executed, the thread 849 will wait for data to come through the InputStream. When {@link 850 java.io.InputStream#read(byte[])} returns with 851 bytes from the stream, the data is sent to the main Activity using a member 852 Handler from the parent class. Then it goes back and waits for more bytes from 853 the stream.</p> 854 855 <p>Sending outgoing data is as simple as calling the thread's 856 <code>write()</code> method from the main Activity and passing in the bytes to 857 be sent. This method then simply calls {@link 858 java.io.OutputStream#write(byte[])} to send the data to the remote device.</p> 859 860 <p>The thread's <code>cancel()</code> method is important so that the connection 861 can be 862 terminated at any time by closing the {@link android.bluetooth.BluetoothSocket}. 863 This should always be called when you're done using the Bluetooth 864 connection.</p> 865 866 <div class="special"> 867 <p>For a demonstration of using the Bluetooth APIs, see the <a 868 href="{@docRoot}resources/samples/BluetoothChat/index.html">Bluetooth Chat sample app</a>.</p> 869 </div> 870 871 <h2 id="Profiles">Working with Profiles</h2> 872 873 <p>Starting in Android 3.0, the Bluetooth API includes support for working with 874 Bluetooth profiles. A <em>Bluetooth profile</em> is a wireless interface 875 specification for Bluetooth-based communication between devices. An example 876 is the Hands-Free profile. For a mobile phone to connect to a wireless headset, 877 both devices must support the Hands-Free profile. </p> 878 879 <p>You can implement the interface {@link android.bluetooth.BluetoothProfile} to write 880 your own classes to support a particular Bluetooth profile. The Android 881 Bluetooth API provides implementations for the following Bluetooth 882 profiles:</p> 883 <ul> 884 885 <li><strong>Headset</strong>. The Headset profile provides support for 886 Bluetooth headsets to be used with mobile phones. Android provides the {@link 887 android.bluetooth.BluetoothHeadset} class, which is a proxy for controlling the 888 Bluetooth Headset Service via interprocess communication (<a 889 href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#IPC">IPC</a 890 >). This includes both Bluetooth Headset and Hands-Free (v1.5) profiles. The 891 {@link android.bluetooth.BluetoothHeadset} class includes support for AT commands. 892 For more discussion of this topic, see <a href="#AT-Commands">Vendor-specific AT commands</a></li> 893 894 <li><strong>A2DP</strong>. The Advanced Audio Distribution Profile (A2DP) 895 profile defines how high quality audio can be streamed from one device to 896 another over a Bluetooth connection. Android provides the {@link 897 android.bluetooth.BluetoothA2dp} class, which is a proxy for controlling 898 the Bluetooth A2DP Service via IPC.</li> 899 900 </ul> 901 902 <p>Here are the basic steps for working with a profile:</p> 903 <ol> 904 905 <li>Get the default adapter, as described in <a href="{@docRoot}guide/topics/wireless/bluetooth. 906 html#SettingUp">Setting Up Bluetooth</a>.</li> 907 908 <li>Use {@link 909 android.bluetooth.BluetoothAdapter#getProfileProxy(android.content.Context, 910 android.bluetooth.BluetoothProfile.ServiceListener, int) getProfileProxy()} to 911 establish a connection to the profile proxy object associated with the profile. 912 In the example below, the profile proxy object is an instance of {@link 913 android.bluetooth.BluetoothHeadset}. </li> 914 915 <li>Set up a {@link android.bluetooth.BluetoothProfile.ServiceListener}. This 916 listener notifies {@link android.bluetooth.BluetoothProfile} IPC clients when 917 they have been connected to or disconnected from the service.</li> 918 919 <li>In {@link 920 android.bluetooth.BluetoothProfile.ServiceListener#onServiceConnected(int, 921 android.bluetooth.BluetoothProfile) onServiceConnected()}, get a handle 922 to the profile proxy object.</li> 923 924 <li>Once you have the profile proxy object, you can use it to monitor the 925 state of the connection and perform other operations that are relevant to that 926 profile.</li> 927 </ol> 928 <p> For example, this code snippet shows how to connect to a {@link android.bluetooth.BluetoothHeadset} proxy object so that you can control the 929 Headset profile:</p> 930 931 <pre>BluetoothHeadset mBluetoothHeadset; 932 933 // Get the default adapter 934 BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 935 936 // Establish connection to the proxy. 937 mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET); 938 939 private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() { 940 public void onServiceConnected(int profile, BluetoothProfile proxy) { 941 if (profile == BluetoothProfile.HEADSET) { 942 mBluetoothHeadset = (BluetoothHeadset) proxy; 943 } 944 } 945 public void onServiceDisconnected(int profile) { 946 if (profile == BluetoothProfile.HEADSET) { 947 mBluetoothHeadset = null; 948 } 949 } 950 }; 951 952 // ... call functions on mBluetoothHeadset 953 954 // Close proxy connection after use. 955 mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset); 956 </pre> 957 958 <h3 id="AT-Commands">Vendor-specific AT commands</h3> 959 960 <p>Starting in Android 3.0, applications can register to receive system 961 broadcasts of pre-defined vendor-specific AT commands sent by headsets (such as 962 a Plantronics +XEVENT command). For example, an application could receive 963 broadcasts that indicate a connected device's battery level and could notify the 964 user or take other action as needed. Create a broadcast receiver for the {@link 965 android.bluetooth.BluetoothHeadset#ACTION_VENDOR_SPECIFIC_HEADSET_EVENT} intent 966 to handle vendor-specific AT commands for the headset.</p> 967