0% found this document useful (0 votes)
190 views21 pages

Public Final Class

The BluetoothAdapter class represents the local Bluetooth adapter on an Android device. It allows applications to perform basic Bluetooth tasks like discovering nearby devices, querying paired devices, and creating Bluetooth connections. To access the local adapter, call BluetoothAdapter.getDefaultAdapter(). This gives access to methods for starting device discovery, getting a list of paired devices, and creating Bluetooth sockets. It also broadcasts intents on events like state changes and discovery completion.

Uploaded by

Abhishek Chaubey
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
190 views21 pages

Public Final Class

The BluetoothAdapter class represents the local Bluetooth adapter on an Android device. It allows applications to perform basic Bluetooth tasks like discovering nearby devices, querying paired devices, and creating Bluetooth connections. To access the local adapter, call BluetoothAdapter.getDefaultAdapter(). This gives access to methods for starting device discovery, getting a list of paired devices, and creating Bluetooth sockets. It also broadcasts intents on events like state changes and discovery completion.

Uploaded by

Abhishek Chaubey
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

public final class

BluetoothAdapter
extends Object
java.lang.Object
    android.bluetooth.BluetoothAdapter

Class Overview
Represents the local device Bluetooth adapter. The BluetoothAdapter lets you perform
fundamental Bluetooth tasks, such as initiate device discovery, query a list of bonded (paired)
devices, instantiate a BluetoothDevice using a known MAC address, and create
a BluetoothServerSocket to listen for connection requests from other devices.

To get a BluetoothAdapter representing the local Bluetooth adapter, call the


static getDefaultAdapter() method. Fundamentally, this is your starting point for all
Bluetooth actions. Once you have the local adapter, you can get a set
of BluetoothDevice objects representing all paired devices with getBondedDevices();
start device discovery withstartDiscovery(); or create a BluetoothServerSocket to
listen for incoming connection requests
with listenUsingRfcommWithServiceRecord(String, UUID).

Note: Most methods require the BLUETOOTH permission and some also require


the BLUETOOTH_ADMIN permission.

See Also

 BluetoothDevice
 BluetoothServerSocket

Summary

Constants

Strin ACTION_CONNECTION_STATE_CHANGED Intent used to broadcast the change in connec


g of the remote device.

Strin ACTION_DISCOVERY_FINISHED Broadcast Action: The local Bluetooth adapte


g

Strin ACTION_DISCOVERY_STARTED Broadcast Action: The local Bluetooth adapte


g

Strin ACTION_LOCAL_NAME_CHANGED Broadcast Action: The local Bluetooth adapte


g

Strin ACTION_REQUEST_DISCOVERABLE Activity Action: Show a system activity that


g

Strin ACTION_REQUEST_ENABLE Activity Action: Show a system activity that


g

Strin ACTION_SCAN_MODE_CHANGED Broadcast Action: Indicates the Bluetooth sca


g

Strin ACTION_STATE_CHANGED Broadcast Action: The state of the local Blue


g

int ERROR Sentinel error value for this class.

Strin EXTRA_CONNECTION_STATE Extra used by ACTION_CONNECTION_S


g connection state.

Strin EXTRA_DISCOVERABLE_DURATION Used as an optional int extra field in ACTIO


g a specific duration for discoverability in seco

Strin EXTRA_LOCAL_NAME Used as a String extra field in ACTION_LO


g Bluetooth name.

Strin EXTRA_PREVIOUS_CONNECTION_STATE Extra used by ACTION_CONNECTION_S


g previous connection state.

Strin EXTRA_PREVIOUS_SCAN_MODE Used as an int extra field in ACTION_SCAN


g scan mode.

Strin EXTRA_PREVIOUS_STATE Used as an int extra field in ACTION_STAT


g state.

Strin EXTRA_SCAN_MODE Used as an int extra field in ACTION_SCAN


g scan mode.

Strin EXTRA_STATE Used as an int extra field in ACTION_STAT


g state.

int SCAN_MODE_CONNECTABLE Indicates that inquiry scan is disabled, but pa

int SCAN_MODE_CONNECTABLE_DISCOVERABLE Indicates that both inquiry scan and page sca

int SCAN_MODE_NONE Indicates that both inquiry scan and page sca

int STATE_CONNECTED The profile is in connected state

int STATE_CONNECTING The profile is in connecting state

int STATE_DISCONNECTED The profile is in disconnected state

int STATE_DISCONNECTING The profile is in disconnecting state

int STATE_OFF Indicates the local Bluetooth adapter is off.

int STATE_ON Indicates the local Bluetooth adapter is on, an

int STATE_TURNING_OFF Indicates the local Bluetooth adapter is turnin

int STATE_TURNING_ON Indicates the local Bluetooth adapter is turnin


Public Methods

boolean cancelDiscovery()
Cancel the current device discovery process.

static boolean checkBluetoothAddress(String address)


Validate a Bluetooth address, such as "00:43:A8:23:10:F0"
Alphabetic characters must be uppercase to be valid.

void closeProfileProxy(int profile, BluetoothProfile proxy)


Close the connection of the profile proxy to the Service.

boolean disable()
Turn off the local Bluetooth adapter—do not use without explicit user action to turn of

boolean enable()
Turn on the local Bluetooth adapter—do not use without explicit user action to turn on

String getAddress()
Returns the hardware address of the local Bluetooth adapter.

Set<BluetoothDevice> getBondedDevices()
Return the set of BluetoothDevice objects that are bonded (paired) to the local

synchronized getDefaultAdapter()
static BluetoothAdapte Get a handle to the default local Bluetooth adapter.
r

String getName()
Get the friendly Bluetooth name of the local Bluetooth adapter.

boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener, int profile)


Get the profile proxy object associated with the profile.

BluetoothDevice getRemoteDevice(String address)
Get a BluetoothDevice object for the given Bluetooth hardware address.

int getScanMode()
Get the current Bluetooth scan mode of the local Bluetooth adapter.

int getState()
Get the current state of the local Bluetooth adapter.

boolean isDiscovering()
Return true if the local Bluetooth adapter is currently in the device discovery process.

boolean isEnabled()
Return true if Bluetooth is currently enabled and ready for use.

BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid)
Create a listening, insecure RFCOMM Bluetooth socket with Service Record.

BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid)
Create a listening, secure RFCOMM Bluetooth socket with Service Record.

boolean setName(String name)
Set the friendly Bluetooth name of the local Bluetooth adapter.
boolean startDiscovery()
Start the remote device discovery process.

[Expand]
Inherited Methods

 From class java.lang.Object

Constants

public static final String ACTION_CONNECTION_STATE_CHANGED


Since: API Level 11
Intent used to broadcast the change in connection state of the local Bluetooth adapter to a profile of
the remote device. When the adapter is not connected to any profiles of any remote devices and it
attempts a connection to a profile this intent will sent. Once connected, this intent will not be sent for
any more connection attempts to any profiles of any remote device. When the adapter disconnects
from the last profile its connected to of any remote device, this intent will be sent.

This intent is useful for applications that are only concerned about whether the local adapter is
connected to any profile of any device and are not really concerned about which profile. For example,
an application which displays an icon to display whether Bluetooth is connected or not can use this
intent.

This intent will have 3 extras: EXTRA_CONNECTION_STATE - The current connection


state. EXTRA_PREVIOUS_CONNECTION_STATE- The previous connection
state. EXTRA_DEVICE- The remote
device. EXTRA_CONNECTION_STATE or EXTRA_PREVIOUS_CONNECTION_STATE can
be any
of STATE_DISCONNECTED, STATE_CONNECTING, STATE_CONNECTED,STATE_DISC
ONNECTING.
Requires BLUETOOTH to receive.

Constant Value: "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED"

public static final String ACTION_DISCOVERY_FINISHED


Since: API Level 5
Broadcast Action: The local Bluetooth adapter has finished the device discovery process.

Requires BLUETOOTH to receive.

Constant Value: "android.bluetooth.adapter.action.DISCOVERY_FINISHED"

public static final String ACTION_DISCOVERY_STARTED


Since: API Level 5
Broadcast Action: The local Bluetooth adapter has started the remote device discovery process.

This usually involves an inquiry scan of about 12 seconds, followed by a page scan of each new
device to retrieve its Bluetooth name.
Register for ACTION_FOUND to be notified as remote Bluetooth devices are found.

Device discovery is a heavyweight procedure. New connections to remote Bluetooth devices should
not be attempted while discovery is in progress, and existing connections will experience limited
bandwidth and high latency. Use cancelDiscovery() to cancel an ongoing discovery.

Requires BLUETOOTH to receive.

Constant Value: "android.bluetooth.adapter.action.DISCOVERY_STARTED"

public static final String ACTION_LOCAL_NAME_CHANGED


Since: API Level 5
Broadcast Action: The local Bluetooth adapter has changed its friendly Bluetooth name.

This name is visible to remote Bluetooth devices.

Always contains the extra field EXTRA_LOCAL_NAME containing the name.

Requires BLUETOOTH to receive.

Constant Value: "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED"

public static final String ACTION_REQUEST_DISCOVERABLE


Since: API Level 5
Activity Action: Show a system activity that requests discoverable mode. This activity will also request
the user to turn on Bluetooth if it is not currently enabled.

Discoverable mode is equivalent to SCAN_MODE_CONNECTABLE_DISCOVERABLE. It allows


remote devices to see this Bluetooth adapter when they perform a discovery.

For privacy, Android is not discoverable by default.

The sender of this Intent can optionally use extra field EXTRA_DISCOVERABLE_DURATION to


request the duration of discoverability. Currently the default duration is 120 seconds, and maximum
duration is capped at 300 seconds for each request.

Notification of the result of this activity is posted using the onActivityResult(int, int,


Intent) callback. The resultCode will be the duration (in seconds) of discoverability
or RESULT_CANCELED if the user rejected discoverability or an error has occurred.

Applications can also listen for ACTION_SCAN_MODE_CHANGED for global notification whenever


the scan mode changes. For example, an application can be notified when the device has ended
discoverability.

Requires BLUETOOTH

Constant Value: "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE"

public static final String ACTION_REQUEST_ENABLE


Since: API Level 5
Activity Action: Show a system activity that allows the user to turn on Bluetooth.

This system activity will return once Bluetooth has completed turning on, or the user has decided not
to turn Bluetooth on.
Notification of the result of this activity is posted using the onActivityResult(int,
int,
Intent) callback. The resultCode will be RESULT_OK if Bluetooth has been turned on
or RESULT_CANCELED if the user has rejected the request or an error has occurred.

Applications can also listen for ACTION_STATE_CHANGED for global notification whenever


Bluetooth is turned on or off.

Requires BLUETOOTH

Constant Value: "android.bluetooth.adapter.action.REQUEST_ENABLE"

public static final String ACTION_SCAN_MODE_CHANGED


Since: API Level 5
Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter has changed.

Always contains the extra


fields EXTRA_SCAN_MODE and EXTRA_PREVIOUS_SCAN_MODE containing the new and old
scan modes respectively.

Requires BLUETOOTH

Constant Value: "android.bluetooth.adapter.action.SCAN_MODE_CHANGED"

public static final String ACTION_STATE_CHANGED


Since: API Level 5
Broadcast Action: The state of the local Bluetooth adapter has been changed.

For example, Bluetooth has been turned on or off.

Always contains the extra fields EXTRA_STATE and EXTRA_PREVIOUS_STATE containing


the new and old states respectively.

Requires BLUETOOTH to receive.

Constant Value: "android.bluetooth.adapter.action.STATE_CHANGED"

public static final int ERROR


Since: API Level 5
Sentinel error value for this class. Guaranteed to not equal any other integer constant in this class.
Provided as a convenience for functions that require a sentinel error value, for example:

Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)

Constant Value: -2147483648 (0x80000000)

public static final String EXTRA_CONNECTION_STATE


Since: API Level 11
Extra used by ACTION_CONNECTION_STATE_CHANGED This extra represents the current
connection state.

Constant Value: "android.bluetooth.adapter.extra.CONNECTION_STATE"

public static final String EXTRA_DISCOVERABLE_DURATION


Since: API Level 5
Used as an optional int extra field in ACTION_REQUEST_DISCOVERABLE intents to request a
specific duration for discoverability in seconds. The current default is 120 seconds, and requests over
300 seconds will be capped. These values could change.

Constant Value: "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION"

public static final String EXTRA_LOCAL_NAME


Since: API Level 5
Used as a String extra field in ACTION_LOCAL_NAME_CHANGED intents to request the local
Bluetooth name.

Constant Value: "android.bluetooth.adapter.extra.LOCAL_NAME"

public static final String EXTRA_PREVIOUS_CONNECTION_STATE


Since: API Level 11
Extra used by ACTION_CONNECTION_STATE_CHANGED This extra represents the previous
connection state.

Constant Value: "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE"

public static final String EXTRA_PREVIOUS_SCAN_MODE


Since: API Level 5
Used as an int extra field in ACTION_SCAN_MODE_CHANGED intents to request the previous
scan mode. Possible values
are: SCAN_MODE_NONE, SCAN_MODE_CONNECTABLE,SCAN_MODE_CONNECTABLE_D
ISCOVERABLE,
Constant Value: "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE"

public static final String EXTRA_PREVIOUS_STATE


Since: API Level 5
Used as an int extra field in ACTION_STATE_CHANGED intents to request the previous power
state. Possible values
are: STATE_OFF, STATE_TURNING_ON, STATE_ON,STATE_TURNING_OFF,

Constant Value: "android.bluetooth.adapter.extra.PREVIOUS_STATE"

public static final String EXTRA_SCAN_MODE


Since: API Level 5
Used as an int extra field in ACTION_SCAN_MODE_CHANGED intents to request the current scan
mode. Possible values
are: SCAN_MODE_NONE, SCAN_MODE_CONNECTABLE,SCAN_MODE_CONNECTABLE_D
ISCOVERABLE,
Constant Value: "android.bluetooth.adapter.extra.SCAN_MODE"

public static final String EXTRA_STATE


Since: API Level 5
Used as an int extra field in ACTION_STATE_CHANGED intents to request the current power
state. Possible values
are: STATE_OFF, STATE_TURNING_ON, STATE_ON,STATE_TURNING_OFF,

Constant Value: "android.bluetooth.adapter.extra.STATE"

public static final int SCAN_MODE_CONNECTABLE


Since: API Level 5
Indicates that inquiry scan is disabled, but page scan is enabled on the local Bluetooth adapter.
Therefore this device is not discoverable from remote Bluetooth devices, but is connectable from
remote devices that have previously discovered this device.

Constant Value: 21 (0x00000015)

public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE


Since: API Level 5
Indicates that both inquiry scan and page scan are enabled on the local Bluetooth adapter. Therefore
this device is both discoverable and connectable from remote Bluetooth devices.

Constant Value: 23 (0x00000017)

public static final int SCAN_MODE_NONE


Since: API Level 5
Indicates that both inquiry scan and page scan are disabled on the local Bluetooth adapter. Therefore
this device is neither discoverable nor connectable from remote Bluetooth devices.

Constant Value: 20 (0x00000014)

public static final int STATE_CONNECTED


Since: API Level 11
The profile is in connected state

Constant Value: 2 (0x00000002)

public static final int STATE_CONNECTING


Since: API Level 11
The profile is in connecting state

Constant Value: 1 (0x00000001)

public static final int STATE_DISCONNECTED


Since: API Level 11
The profile is in disconnected state

Constant Value: 0 (0x00000000)

public static final int STATE_DISCONNECTING


Since: API Level 11
The profile is in disconnecting state

Constant Value: 3 (0x00000003)


public static final int STATE_OFF
Since: API Level 5
Indicates the local Bluetooth adapter is off.

Constant Value: 10 (0x0000000a)

public static final int STATE_ON


Since: API Level 5
Indicates the local Bluetooth adapter is on, and ready for use.

Constant Value: 12 (0x0000000c)

public static final int STATE_TURNING_OFF


Since: API Level 5
Indicates the local Bluetooth adapter is turning off. Local clients should immediately attempt graceful
disconnection of any remote links.

Constant Value: 13 (0x0000000d)

public static final int STATE_TURNING_ON


Since: API Level 5
Indicates the local Bluetooth adapter is turning on. However local clients should wait
for STATE_ON before attempting to use the adapter.

Constant Value: 11 (0x0000000b)

Public Methods
public boolean cancelDiscovery ()
Since: API Level 5
Cancel the current device discovery process.

Requires BLUETOOTH_ADMIN.

Because discovery is a heavyweight procedure for the Bluetooth adapter, this method should always
be called before attempting to connect to a remote device with connect(). Discovery is not
managed by the Activity, but is run as a system service, so an application should always call cancel
discovery even if it did not directly request a discovery, just to be sure.

If Bluetooth state is not STATE_ON, this API will return false. After turning on Bluetooth, wait
for ACTION_STATE_CHANGED with STATE_ON to get the updated value.

Returns

 true on success, false on error

public static boolean checkBluetoothAddress (String address)


Since: API Level 5
Validate a Bluetooth address, such as "00:43:A8:23:10:F0"
Alphabetic characters must be uppercase to be valid.

Parameters

addres Bluetooth address as string


s

Returns

 true if the address is valid, false otherwise

public void closeProfileProxy (int profile, BluetoothProfile proxy)


Since: API Level 11
Close the connection of the profile proxy to the Service.

Clients should call this when they are no longer using the proxy obtained
from getProfileProxy(Context, BluetoothProfile.ServiceListener,
int). Profile can be one of HEADSET or A2DP

Parameters

prox Profile proxy object


y

public boolean disable ()
Since: API Level 5
Turn off the local Bluetooth adapter—do not use without explicit user action to turn off Bluetooth.

This gracefully shuts down all Bluetooth connections, stops Bluetooth system services, and powers
down the underlying Bluetooth hardware.

Bluetooth should never be disabled without direct user consent .


The disable() method is provided only for applications that include a user interface for
changing system settings, such as a "power manager" app.

This is an asynchronous call: it will return immediately, and clients should listen
for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call
returns true, then the adapter state will immediately transition
from STATE_ON to STATE_TURNING_OFF, and some time later transition to
either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem
that will prevent the adapter from being turned off - such as the adapter already being turned off.

Requires the BLUETOOTH_ADMIN permission

Returns

 true to indicate adapter shutdown has begun, or false on immediate error

public boolean enable ()
Since: API Level 5
Turn on the local Bluetooth adapter—do not use without explicit user action to turn on Bluetooth.
This powers on the underlying Bluetooth hardware, and starts all Bluetooth system services.

Bluetooth should never be enabled without direct user consent . If you want
to turn on Bluetooth in order to create a wireless connection, you should use
theACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user
permission to turn on Bluetooth. The enable() method is provided only for applications that
include a user interface for changing system settings, such as a "power manager" app.

This is an asynchronous call: it will return immediately, and clients should listen
for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call
returns true, then the adapter state will immediately transition
from STATE_OFF to STATE_TURNING_ON, and some time later transition to
either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem
that will prevent the adapter from being turned on - such as Airplane mode, or the adapter is already
turned on.

Requires the BLUETOOTH_ADMIN permission

Returns

 true to indicate adapter startup has begun, or false on immediate error

public String getAddress ()
Since: API Level 5
Returns the hardware address of the local Bluetooth adapter.

For example, "00:11:22:AA:BB:CC".

Requires BLUETOOTH

Returns

 Bluetooth hardware address as string

public Set<BluetoothDevice> getBondedDevices ()
Since: API Level 5
Return the set of BluetoothDevice objects that are bonded (paired) to the local adapter.

If Bluetooth state is not STATE_ON, this API will return an empty set. After turning on Bluetooth, wait
for ACTION_STATE_CHANGED with STATE_ON to get the updated value.

Requires BLUETOOTH.

Returns

 unmodifiable set of BluetoothDevice, or null on error

public static synchronized BluetoothAdapter getDefaultAdapter ()


Since: API Level 5
Get a handle to the default local Bluetooth adapter.
Currently Android only supports one Bluetooth adapter, but the API could be extended to support
more. This will always return the default adapter.

Returns

 the default local adapter, or null if Bluetooth is not supported on this hardware platform

public String getName ()
Since: API Level 5
Get the friendly Bluetooth name of the local Bluetooth adapter.

This name is visible to remote Bluetooth devices.

Requires BLUETOOTH

Returns

 the Bluetooth name, or null on error

public boolean getProfileProxy (Context context, BluetoothProfile.ServiceListener listener,
int profile)
Since: API Level 11
Get the profile proxy object associated with the profile.

Profile can be one of HEADSET or A2DP. Clients must


implements BluetoothProfile.ServiceListener to get notified of the connection
status and to get the proxy object.

Parameters

context Context of the application


listene The service Listener for connection callbacks.
r
profile The Bluetooth profile; either HEADSET or A2DP.

Returns

 true on success, false on error

public BluetoothDevice getRemoteDevice (String address)
Since: API Level 5
Get a BluetoothDevice object for the given Bluetooth hardware address.

Valid Bluetooth hardware addresses must be upper case, in a format such as "00:11:22:33:AA:BB".
The helper checkBluetoothAddress(String) is available to validate a Bluetooth
address.

A BluetoothDevice will always be returned for a valid hardware address, even if this adapter
has never seen that device.

Parameters
addres valid Bluetooth MAC address
s

Throws

IllegalArgumentExceptio if address is invalid


n

public int getScanMode ()
Since: API Level 5
Get the current Bluetooth scan mode of the local Bluetooth adapter.

The Bluetooth scan mode determines if the local adapter is connectable and/or discoverable from
remote Bluetooth devices.

Possible values
are: SCAN_MODE_NONE, SCAN_MODE_CONNECTABLE, SCAN_MODE_CONNECTABLE_D
ISCOVERABLE.
If Bluetooth state is not STATE_ON, this API will return SCAN_MODE_NONE. After turning on
Bluetooth, wait for ACTION_STATE_CHANGED with STATE_ON to get the updated value.

Requires BLUETOOTH

Returns

 scan mode

public int getState ()
Since: API Level 5
Get the current state of the local Bluetooth adapter.

Possible return values


are STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF.

Requires BLUETOOTH

Returns

 current state of Bluetooth adapter

public boolean isDiscovering ()
Since: API Level 5
Return true if the local Bluetooth adapter is currently in the device discovery process.

Device discovery is a heavyweight procedure. New connections to remote Bluetooth devices should
not be attempted while discovery is in progress, and existing connections will experience limited
bandwidth and high latency. Use cancelDiscovery() to cancel an ongoing discovery.

Applications can also register


for ACTION_DISCOVERY_STARTED or ACTION_DISCOVERY_FINISHED to be notified
when discovery starts or completes.
If Bluetooth state is not STATE_ON, this API will return false. After turning on Bluetooth, wait
for ACTION_STATE_CHANGED with STATE_ON to get the updated value.

Requires BLUETOOTH.

Returns

 true if discovering

public boolean isEnabled ()
Since: API Level 5
Return true if Bluetooth is currently enabled and ready for use.

Equivalent to: getBluetoothState() == STATE_ON

Requires BLUETOOTH

Returns

 true if the local adapter is turned on

public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord (String n
ame, UUID uuid)
Since: API Level 10
Create a listening, insecure RFCOMM Bluetooth socket with Service Record.

The link key will be unauthenticated i.e the communication is vulnerable to Man In the Middle attacks.
For Bluetooth 2.1 devices, the link key will be encrypted, as encryption is mandartory. For legacy
devices (pre Bluetooth 2.1 devices) the link key will not be encrypted.
Use listenUsingRfcommWithServiceRecord(String, UUID), if an encrypted
and authenticated communication channel is desired.

Use accept() to retrieve incoming connections from a


listening BluetoothServerSocket.

The system will assign an unused RFCOMM channel to listen on.

The system will also register a Service Discovery Protocol (SDP) record with the local SDP server
containing the specified UUID, service name, and auto-assigned channel. Remote Bluetooth devices
can use the same UUID to query our SDP server and discover which channel to connect to. This SDP
record will be removed when this socket is closed, or if this application closes unexpectedly.

Use createRfcommSocketToServiceRecord(UUID) to connect to this socket from


another device using the same UUID.

Requires BLUETOOTH

Parameters

nam service name for SDP record


e
uuid uuid for SDP record
Returns

 a listening RFCOMM BluetoothServerSocket

Throws

IOExceptio on error, for example Bluetooth not available, or insufficient permissions,


n or channel in use.

public BluetoothServerSocket listenUsingRfcommWithServiceRecord (String name, UUI
D uuid)
Since: API Level 5
Create a listening, secure RFCOMM Bluetooth socket with Service Record.

A remote device connecting to this socket will be authenticated and communication on this socket will
be encrypted.

Use accept() to retrieve incoming connections from a


listening BluetoothServerSocket.

The system will assign an unused RFCOMM channel to listen on.

The system will also register a Service Discovery Protocol (SDP) record with the local SDP server
containing the specified UUID, service name, and auto-assigned channel. Remote Bluetooth devices
can use the same UUID to query our SDP server and discover which channel to connect to. This SDP
record will be removed when this socket is closed, or if this application closes unexpectedly.

Use createRfcommSocketToServiceRecord(UUID) to connect to this socket from


another device using the same UUID.

Requires BLUETOOTH

Parameters

nam service name for SDP record


e
uuid uuid for SDP record

Returns

 a listening RFCOMM BluetoothServerSocket

Throws

IOExceptio on error, for example Bluetooth not available, or insufficient permissions,


n or channel in use.

public boolean setName (String name)
Since: API Level 5
Set the friendly Bluetooth name of the local Bluetooth adapter.

This name is visible to remote Bluetooth devices.


Valid Bluetooth names are a maximum of 248 bytes using UTF-8 encoding, although many remote
devices can only display the first 40 characters, and some may be limited to just 20.

If Bluetooth state is not STATE_ON, this API will return false. After turning on Bluetooth, wait
for ACTION_STATE_CHANGED with STATE_ON to get the updated value.

Requires BLUETOOTH_ADMIN

Parameters

nam a valid Bluetooth name


e

Returns

 true if the name was set, false otherwise

public boolean startDiscovery ()
Since: API Level 5
Start the remote device discovery process.

The discovery process usually involves an inquiry scan of about 12 seconds, followed by a page scan
of each new device to retrieve its Bluetooth name.

This is an asynchronous call, it will return immediately. Register


for ACTION_DISCOVERY_STARTED and ACTION_DISCOVERY_FINISHED intents to
determine exactly when the discovery starts and completes. Register for ACTION_FOUND to be
notified as remote Bluetooth devices are found.

Device discovery is a heavyweight procedure. New connections to remote Bluetooth devices should
not be attempted while discovery is in progress, and existing connections will experience limited
bandwidth and high latency. Use cancelDiscovery() to cancel an ongoing discovery.
Discovery is not managed by the Activity, but is run as a system service, so an application should
always call cancelDiscovery() even if it did not directly request a discovery, just to be sure.

Device discovery will only find remote devices that are currently discoverable (inquiry scan enabled).
Many Bluetooth devices are not discoverable by default, and need to be entered into a special mode.

If Bluetooth state is not STATE_ON, this API will return false. After turning on Bluetooth, wait
for ACTION_STATE_CHANGED with STATE_ON to get the updated value.

Requires BLUETOOTH_ADMIN.

Returns

 true on success, false on error


[+] Enlarge Image
Figure 1. Bluetooth Server Application

Creating a Bluetooth Client Application


Complete the following steps to develop a Bluetooth client application.

1. Request a connection to Bluetooth server – Use the Bluetooth Open Connection function
to connect to a service on a Bluetooth server. Set the channel number to zero and specify a
Bluetooth uuid to identify which service to connect to. The Bluetooth Open Connection
function performs an SDP query to make a connection to the first service found with
matching uuid. Internally, the result of an SDP query is an RFCOMM channel number to
connect to. The SDP query is a tool to "translate" uuid to a channel number.

If you know the channel number associated with the service in advance, use the channel
number instead of zero. Specifying a nonzero channel number bypasses the internal SDP
query operation thus reducing the amount of time it takes to connect to the service. If the
channel number is nonzero, LabVIEW ignores the uuid input parameter.

Note: You can use the Bluetooth RFCOMM Service Discovery VI to search for a valid
channel number associated with a service on a remote Bluetooth device. This VI performs an
SDP RFCOMM service discovery resulting in a channel number you can use to connect to
the corresponding service on the remote Bluetooth device.

2. Read and Write data – Use Bluetooth Read and Bluetooth Write functions to exchange
data with the server.

3. Close connection – Use Bluetooth Close Connection function to close connection to the
server.

The block diagram of a typical Bluetooth client application looks similar to Figure 2.
[+] Enlarge Image
Figure 2. Bluetooth Client Application

Refer to the following VIs for examples of creating a simple Bluetooth server and client
applications:

 Simple Bluetooth Server VI: labview\examples\comm\Bluetooth.llb


 Simple Bluetooth Client VI: labview\examples\comm\Bluetooth.llb
 Simple Bluetooth Server (Palm OS) VI: labview\examples\PDA\pdacomm\PDABluetooth.llb
 Simple Bluetooth Client (Palm OS) VI: labview\examples\PDA\pdacomm\PDABluetooth.llb
 Simple Bluetooth Server (Pocket PC) VI: labview\examples\PDA\pdacomm\PDABluetooth.llb
 Simple Bluetooth Client (Pocket PC) VI: labview\examples\PDA\pdacomm\PDABluetooth.llb

Finding Nearby Bluetooth Devices


Use the Bluetooth Discover function to search for Bluetooth devices that are within the
permissible range. The function returns a list of device addresses and names. These device
addresses can then be used by a client to connect to a specific Bluetooth server. The optional
input parameter, time limit (ms), specifies the length of Bluetooth inquiry. The default value
is 10 ms and the maximum value is 30 s. If time limit is less than or equal to zero, the
function returns a list of installed local Bluetooth devices.

Note: Bluetooth discovery is a slow operation because of the communication involved. A


Bluetooth device address is a fixed address that is usually printed on the actual device and
you can query the address from the device control setting. This address is unique to each
device. If you know the Bluetooth address of the specific device you want to connect to, you
can skip the discovery process and use the Bluetooth Open Connection function to connect
to the device directly.

Querying Services Available on a Bluetooth Device

Use the Bluetooth RFCOMM Service Discovery VI to search for available RFCOMM
services on a local/remote Bluetooth device. This function returns a list of available services
along with the associated channel numbers. A channel number in the list can be used as an
input parameter of the Bluetooth Open Connection function to make a connection to the
corresponding service on the remote Bluetooth device.
Figure 3. Bluetooth Discovery Function

Refer to the following VIs for examples of Bluetooth device and service discovery:

 Advanced Bluetooth Server.vi: labview\examples\comm\Bluetooth.llb


 Advanced Bluetooth Client.vi: labview\examples\comm\Bluetooth.llb
 Advanced Bluetooth Client – PDA.vi: labview\examples\PDA\pdacomm\PDABluetoothllb

Bluetooth Virtual Serial Port


A Bluetooth system in PalmOS and PocketPC provides serial port profile with a virtual serial
driver. Bluetooth Serial Port profile defines procedures that devices use to emulate an RS-
232/serial cable connection. The profile maps virtual Serial COM ports to actual Bluetooth
channels. Bluetooth Serial Port profile enables you to use LabVIEW Serial VIs to open a
connection to and exchange data with other Bluetooth devices. Bluetooth Serial Port profile
cannot be used on Windows XP SP1. Other Windows Bluetooth drivers may work with the
Serial Port profile.

The driver recognizes only one active serial channel at a time. You can open the serial
channel as an outbound (client) port or as an inbound (server) port. When you open the port
as an outbound (client) port, the driver prompts you to select a Bluetooth device (server) to
connect to. When you open the port as an inbound (server) port, the driver waits to receive a
connection request from the client. Bluetooth serial port is based on RFCOMM, which is
different from a physical serial port. RFCOMM requires roles of a server and a client when
establishing Bluetooth serial connection.

Refer to KnowledgeBase 32GEGGTP: Does LabVIEW for PDA Support Bluetooth? (linked
below) for more information on Bluetooth Virtual Serial Port and the LabVIEW PDA
Module.
Related Links:
KnowledgeBase 32GEGGTP: Does LabVIEW for PDA Support Bluetooth?
LabVIEW Development System
LabVIEW PDA Module
Microsoft Website
Bluetooth Website
LabVIEW PDA User Manual

72 ratings | 3.71 out of 5

Print

Reader Comments | Submit a comment »

Bluetooth discovery failure


None of the examples you supplied on http://decibel.ni.com/content/docs/DOC- 7981 does
NOT work with the BlueSoleil dongles
- Oct 26, 2010

Help with client/server/ whitn Bluetooth in LABVIEW


Thanks for the help provided ... I am now investigating how to develop a communication
with bluetooth between a PC with a card that controls a set of relays to perform work of home
automation. I'm thinking of setting up a server on the laptop and a client on the card, plus this
server also has to work with a client installed on a cellular (mobile) having Bluetooth
protocol, if maybe I can help with Labview manual, or with any suggestions, I anticipate my
thanks. thanks.
- [email protected] - Oct 16, 2009

Yes. All very well and good but most of us want to communicate with mobile phones not
another PC running Labview. Bluetooth support in Labview is like RS485 without Profibus
or Modbus. When will there be an OBEX toolkit? I'd love to be able to just walk past my
machines and pick up results data on my phone!
- Apr 5, 2009

How to obtain uuid? What it is? How do we know that?


- Alex Nguyen, qweq. [email protected] - May 29, 2007

The bluetooth support should be extended to CVI also.


- [email protected] - Oct 17, 2006

What about CVI and Measurement Studio?


The support for Bluetooth applications is great? Why have you not put this capabability into
CVI or Measurement Studio?
- Steve Macha, Mikrokraft, Inc.. [email protected] - Mar 21, 2005

Bluetooth VI are good.


Okay, I changed my mind. I can see that having Labview start and stop the Bluetooth services
to the "virtual serial port" is a good thing. It saves on the manual effort of discovering the
Bluetooth services, starting and stopping, etc. through Windows. Especially if the computer is
unattended.
- Craig Hange, NASA Ames Research Center. [email protected] - Jul 23, 2004

Windows Bluetooth Serial Port Service also works.


I was wondering if someone could explain the advantages of putting the Bluetooth access
within Labview? On my Bluetooth equipped computers I can choose to use the Bluetooth as a
virtual serial port through Windows XP and "Discover Bluetooth Services". It then appears as
COM6 or COM7. Nothing needs to be changed in the Labview VI, except the serial port
number. I can still run code that was written years ago for the serial port. This seems easier,
but I may be missing some advantage.
- Craig Hange, NASA Ames Research Center. [email protected] - Jul 23, 2004

Legal
This tutorial (this "tutorial") was developed by National Instruments ("NI"). Although
technical support of this tutorial may be made available by National Instruments, the content
in this tutorial may not be completely tested and verified, and NI does not guarantee its
quality in any way or that NI will continue to support this content with each new revision of
related products and drivers. THIS TUTORIAL IS PROVIDED "AS IS" WITHOUT
WARRANTY OF ANY KIND AND SUBJECT TO CERTAIN RESTRICTIONS AS MORE
SPECIFICALLY SET FORTH IN NI.COM'S TERMS OF USE
(http://ni.com/legal/termsofuse/unitedstates/us/).

You might also like