public final class BluetoothAdapter extends Object
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, and start a scan for Bluetooth LE devices.
To get a BluetoothAdapter
representing the local Bluetooth
adapter, when running on JELLY_BEAN_MR1 and below, call the
static getDefaultAdapter()
method; when running on JELLY_BEAN_MR2 and
higher, call BluetoothManager.getAdapter()
.
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 with
startDiscovery()
; or create a BluetoothServerSocket
to
listen for incoming connection requests with
listenUsingRfcommWithServiceRecord(String,UUID)
; or start a scan for
Bluetooth LE devices with startLeScan(LeScanCallback callback)
.
This class is thread safe.
Note:
Most methods require the android.Manifest.permission#BLUETOOTH
permission and some also require the
android.Manifest.permission#BLUETOOTH_ADMIN
permission.
For more information about using Bluetooth, read the Bluetooth developer guide.
BluetoothDevice
BluetoothServerSocket
Modifier and Type | Class and Description |
---|---|
static interface |
BluetoothAdapter.AdapterState |
static interface |
BluetoothAdapter.BluetoothStateChangeCallback |
static interface |
BluetoothAdapter.LeScanCallback
Callback interface used to deliver LE scan results.
|
static interface |
BluetoothAdapter.ScanMode |
class |
BluetoothAdapter.StateChangeCallbackWrapper |
Modifier and Type | Field and Description |
---|---|
static String |
ACTION_BLE_ACL_CONNECTED
Broadcast Action: The notifys Bluetooth ACL connected event.
|
static String |
ACTION_BLE_ACL_DISCONNECTED
Broadcast Action: The notifys Bluetooth ACL connected event.
|
static String |
ACTION_BLE_STATE_CHANGED
Broadcast Action: The Bluetooth adapter state has changed in LE only mode.
|
static String |
ACTION_CONNECTION_STATE_CHANGED
Intent used to broadcast the change in connection state of the local
Bluetooth adapter to a profile of the remote device.
|
static String |
ACTION_DISCOVERY_FINISHED
Broadcast Action: The local Bluetooth adapter has finished the device
discovery process.
|
static String |
ACTION_DISCOVERY_STARTED
Broadcast Action: The local Bluetooth adapter has started the remote
device discovery process.
|
static String |
ACTION_LOCAL_NAME_CHANGED
Broadcast Action: The local Bluetooth adapter has changed its friendly
Bluetooth name.
|
static String |
ACTION_REQUEST_BLE_SCAN_ALWAYS_AVAILABLE
Activity Action: Show a system activity that allows user to enable BLE scans even when
Bluetooth is turned off.
|
static String |
ACTION_REQUEST_DISCOVERABLE
Activity Action: Show a system activity that requests discoverable mode.
|
static String |
ACTION_REQUEST_ENABLE
Activity Action: Show a system activity that allows the user to turn on
Bluetooth.
|
static String |
ACTION_SCAN_MODE_CHANGED
Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter
has changed.
|
static String |
ACTION_STATE_CHANGED
Broadcast Action: The state of the local Bluetooth adapter has been
changed.
|
static String |
BLUETOOTH_MANAGER_SERVICE |
static String |
DEFAULT_MAC_ADDRESS
Default MAC address reported to a client that does not have the
android.permission.LOCAL_MAC_ADDRESS permission.
|
static int |
ERROR
Sentinel error value for this class.
|
static String |
EXTRA_CONNECTION_STATE
Extra used by
ACTION_CONNECTION_STATE_CHANGED
This extra represents the current connection state. |
static String |
EXTRA_DISCOVERABLE_DURATION
Used as an optional int extra field in
ACTION_REQUEST_DISCOVERABLE intents to request a specific duration
for discoverability in seconds. |
static String |
EXTRA_LOCAL_NAME
Used as a String extra field in
ACTION_LOCAL_NAME_CHANGED
intents to request the local Bluetooth name. |
static String |
EXTRA_PREVIOUS_CONNECTION_STATE
Extra used by
ACTION_CONNECTION_STATE_CHANGED
This extra represents the previous connection state. |
static String |
EXTRA_PREVIOUS_SCAN_MODE
Used as an int extra field in
ACTION_SCAN_MODE_CHANGED
intents to request the previous scan mode. |
static String |
EXTRA_PREVIOUS_STATE
Used as an int extra field in
ACTION_STATE_CHANGED
intents to request the previous power state. |
static String |
EXTRA_SCAN_MODE
Used as an int extra field in
ACTION_SCAN_MODE_CHANGED
intents to request the current scan mode. |
static String |
EXTRA_STATE
Used as an int extra field in
ACTION_STATE_CHANGED
intents to request the current power state. |
static int |
SCAN_MODE_CONNECTABLE
Indicates that inquiry scan is disabled, but page scan is enabled on the
local Bluetooth adapter.
|
static int |
SCAN_MODE_CONNECTABLE_DISCOVERABLE
Indicates that both inquiry scan and page scan are enabled on the local
Bluetooth adapter.
|
static int |
SCAN_MODE_NONE
Indicates that both inquiry scan and page scan are disabled on the local
Bluetooth adapter.
|
static int |
SOCKET_CHANNEL_AUTO_STATIC_NO_SDP
When creating a ServerSocket using listenUsingRfcommOn() or
listenUsingL2capOn() use SOCKET_CHANNEL_AUTO_STATIC to create
a ServerSocket that auto assigns a channel number to the first
bluetooth socket.
|
static int |
STATE_BLE_ON
Indicates the local Bluetooth adapter is in LE only mode.
|
static int |
STATE_BLE_TURNING_OFF
Indicates the local Bluetooth adapter is turning off LE only mode.
|
static int |
STATE_BLE_TURNING_ON
Indicates the local Bluetooth adapter is turning Bluetooth LE mode on.
|
static int |
STATE_CONNECTED
The profile is in connected state
|
static int |
STATE_CONNECTING
The profile is in connecting state
|
static int |
STATE_DISCONNECTED
The profile is in disconnected state
|
static int |
STATE_DISCONNECTING
The profile is in disconnecting state
|
static int |
STATE_OFF
Indicates the local Bluetooth adapter is off.
|
static int |
STATE_ON
Indicates the local Bluetooth adapter is on, and ready for use.
|
static int |
STATE_TURNING_OFF
Indicates the local Bluetooth adapter is turning off.
|
static int |
STATE_TURNING_ON
Indicates the local Bluetooth adapter is turning on.
|
Modifier and Type | Method and Description |
---|---|
boolean |
cancelDiscovery()
Cancel the current device discovery process.
|
boolean |
changeApplicationBluetoothState(boolean on,
BluetoothAdapter.BluetoothStateChangeCallback callback)
Enable control of the Bluetooth Adapter for a single application.
|
static boolean |
checkBluetoothAddress(String address)
Validate a String 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 |
configHciSnoopLog(boolean enable)
enable or disable Bluetooth HCI snoop log.
|
boolean |
disable()
Turn off the local Bluetooth adapter—do not use without explicit
user action to turn off Bluetooth.
|
boolean |
disable(boolean persist)
Turn off the local Bluetooth adapter and don't persist the setting.
|
boolean |
disableBLE()
Turns off Bluetooth LE which was earlier turned on by calling EnableBLE().
|
boolean |
enable()
Turn on the local Bluetooth adapter—do not use without explicit
user action to turn on Bluetooth.
|
boolean |
enableBLE()
Special Applications who want to only turn on Bluetooth Low Energy (BLE) would
EnableBLE, EnableBLE brings-up Bluetooth so that application can access
only LE related feature (Bluetooth GATT layers interfaces using the respective class)
EnableBLE in turn registers the existance of a special App which wants to
turn on Bluetooth Low enrgy part without making it visible at the settings UI
as Bluetooth ON.
|
boolean |
enableNoAutoConnect()
Enable the Bluetooth Adapter, but don't auto-connect devices
and don't persist state.
|
boolean |
factoryReset()
Factory reset bluetooth settings.
|
protected void |
finalize()
Called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.
|
String |
getAddress()
Returns the hardware address of the local Bluetooth adapter.
|
BluetoothLeAdvertiser |
getBluetoothLeAdvertiser()
Returns a
BluetoothLeAdvertiser object for Bluetooth LE Advertising operations. |
BluetoothLeScanner |
getBluetoothLeScanner()
Returns a
BluetoothLeScanner object for Bluetooth LE scan operations. |
Set<BluetoothDevice> |
getBondedDevices()
Return the set of
BluetoothDevice objects that are bonded
(paired) to the local adapter. |
int |
getConnectionState()
Get the current connection state of the local Bluetooth adapter.
|
BluetoothActivityEnergyInfo |
getControllerActivityEnergyInfo(int updateType)
Deprecated.
use the asynchronous
requestControllerActivityEnergyInfo(ResultReceiver) instead. |
static BluetoothAdapter |
getDefaultAdapter()
Get a handle to the default local Bluetooth adapter.
|
int |
getDiscoverableTimeout() |
int |
getLeState()
Get the current state of the local Bluetooth adapter
This returns current internal state of Adapter including LE ON/OFF
Possible return values are
STATE_OFF ,
STATE_BLE_TURNING_ON ,
STATE_BLE_ON ,
STATE_TURNING_ON ,
STATE_ON ,
STATE_TURNING_OFF ,
STATE_BLE_TURNING_OFF . |
String |
getName()
Get the friendly Bluetooth name of the local Bluetooth adapter.
|
int |
getProfileConnectionState(int profile)
Get the current connection state of a profile.
|
boolean |
getProfileProxy(Context context,
BluetoothProfile.ServiceListener listener,
int profile)
Get the profile proxy object associated with the profile.
|
BluetoothDevice |
getRemoteDevice(byte[] address)
Get a
BluetoothDevice object for the given Bluetooth hardware
address. |
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.
|
ParcelUuid[] |
getUuids()
Get the UUIDs supported by the local Bluetooth adapter.
|
boolean |
isBleScanAlwaysAvailable()
Returns
true if BLE scan is always available, false otherwise. |
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.
|
boolean |
isHardwareTrackingFiltersAvailable()
Return true if hardware has entries available for matching beacons
|
boolean |
isLeEnabled()
Return true if Bluetooth LE(Always BLE On feature) is currently
enabled and ready for use
This returns true if current state is either STATE_ON or STATE_BLE_ON
|
boolean |
isMultipleAdvertisementSupported()
Return true if the multi advertisement is supported by the chipset
|
boolean |
isOffloadedFilteringSupported()
Return true if offloaded filters are supported
|
boolean |
isOffloadedScanBatchingSupported()
Return true if offloaded scan batching is supported
|
boolean |
isPeripheralModeSupported()
Returns whether peripheral mode is supported.
|
BluetoothServerSocket |
listenUsingEncryptedRfcommOn(int port)
Construct an encrypted, RFCOMM server socket.
|
BluetoothServerSocket |
listenUsingEncryptedRfcommWithServiceRecord(String name,
UUID uuid)
Create a listening, encrypted,
RFCOMM Bluetooth socket with Service Record.
|
BluetoothServerSocket |
listenUsingInsecureRfcommOn(int port)
Construct an unencrypted, unauthenticated, RFCOMM server socket.
|
BluetoothServerSocket |
listenUsingInsecureRfcommWithServiceRecord(String name,
UUID uuid)
Create a listening, insecure RFCOMM Bluetooth socket with Service Record.
|
BluetoothServerSocket |
listenUsingL2capOn(int port)
Construct an encrypted, authenticated, L2CAP server socket.
|
BluetoothServerSocket |
listenUsingL2capOn(int port,
boolean mitm,
boolean min16DigitPin)
Construct an encrypted, authenticated, L2CAP server socket.
|
BluetoothServerSocket |
listenUsingRfcommOn(int channel)
Create a listening, secure RFCOMM Bluetooth socket.
|
BluetoothServerSocket |
listenUsingRfcommOn(int channel,
boolean mitm,
boolean min16DigitPin)
Create a listening, secure RFCOMM Bluetooth socket.
|
BluetoothServerSocket |
listenUsingRfcommWithServiceRecord(String name,
UUID uuid)
Create a listening, secure RFCOMM Bluetooth socket with Service Record.
|
static BluetoothServerSocket |
listenUsingScoOn()
Construct a SCO server socket.
|
Pair<byte[],byte[]> |
readOutOfBandData()
Read the local Out of Band Pairing Data
Requires
android.Manifest.permission#BLUETOOTH |
void |
requestControllerActivityEnergyInfo(ResultReceiver result)
Request the record of
BluetoothActivityEnergyInfo object that
has the activity and energy info. |
void |
setDiscoverableTimeout(int timeout) |
boolean |
setName(String name)
Set the friendly Bluetooth name of the local Bluetooth adapter.
|
boolean |
setScanMode(int mode) |
boolean |
setScanMode(int mode,
int duration)
Set the Bluetooth scan mode of the local Bluetooth adapter.
|
boolean |
startDiscovery()
Start the remote device discovery process.
|
boolean |
startLeScan(BluetoothAdapter.LeScanCallback callback)
Deprecated.
|
boolean |
startLeScan(UUID[] serviceUuids,
BluetoothAdapter.LeScanCallback callback)
Deprecated.
|
void |
stopLeScan(BluetoothAdapter.LeScanCallback callback)
Deprecated.
Use
BluetoothLeScanner.stopScan(ScanCallback) instead. |
public static final String DEFAULT_MAC_ADDRESS
public static final int ERROR
Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR)
public static final String ACTION_STATE_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 android.Manifest.permission#BLUETOOTH
to receive.
public static final String EXTRA_STATE
ACTION_STATE_CHANGED
intents to request the current power state. Possible values are:
STATE_OFF
,
STATE_TURNING_ON
,
STATE_ON
,
STATE_TURNING_OFF
,public static final String EXTRA_PREVIOUS_STATE
ACTION_STATE_CHANGED
intents to request the previous power state. Possible values are:
STATE_OFF
,
STATE_TURNING_ON
,
STATE_ON
,
STATE_TURNING_OFF
public static final int STATE_OFF
public static final int STATE_TURNING_ON
STATE_ON
before attempting to
use the adapter.public static final int STATE_ON
public static final int STATE_TURNING_OFF
public static final int STATE_BLE_TURNING_ON
public static final int STATE_BLE_ON
public static final int STATE_BLE_TURNING_OFF
public static final String ACTION_REQUEST_DISCOVERABLE
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
Activity.onActivityResult(int, int, android.content.Intent)
callback. The
resultCode
will be the duration (in seconds) of discoverability or
Activity.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 android.Manifest.permission#BLUETOOTH
public static final String EXTRA_DISCOVERABLE_DURATION
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.public static final String ACTION_REQUEST_ENABLE
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
Activity.onActivityResult(int, int, android.content.Intent)
callback. The
resultCode
will be Activity.RESULT_OK
if Bluetooth has been
turned on or Activity.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 android.Manifest.permission#BLUETOOTH
public static final String ACTION_REQUEST_BLE_SCAN_ALWAYS_AVAILABLE
Notification of result of this activity is posted using
Activity.onActivityResult(int, int, android.content.Intent)
. The resultCode
will be
Activity.RESULT_OK
if BLE scan always available setting is turned on or
Activity.RESULT_CANCELED
if the user has rejected the request or an
error occurred.
public static final String ACTION_SCAN_MODE_CHANGED
Always contains the extra fields EXTRA_SCAN_MODE
and EXTRA_PREVIOUS_SCAN_MODE
containing the new and old scan modes
respectively.
Requires android.Manifest.permission#BLUETOOTH
public static final String EXTRA_SCAN_MODE
ACTION_SCAN_MODE_CHANGED
intents to request the current scan mode. Possible values are:
SCAN_MODE_NONE
,
SCAN_MODE_CONNECTABLE
,
SCAN_MODE_CONNECTABLE_DISCOVERABLE
,public static final String EXTRA_PREVIOUS_SCAN_MODE
ACTION_SCAN_MODE_CHANGED
intents to request the previous scan mode. Possible values are:
SCAN_MODE_NONE
,
SCAN_MODE_CONNECTABLE
,
SCAN_MODE_CONNECTABLE_DISCOVERABLE
,public static final int SCAN_MODE_NONE
public static final int SCAN_MODE_CONNECTABLE
public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE
public static final String ACTION_DISCOVERY_STARTED
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 BluetoothDevice.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 android.Manifest.permission#BLUETOOTH
to receive.
public static final String ACTION_DISCOVERY_FINISHED
Requires android.Manifest.permission#BLUETOOTH
to receive.
public static final String ACTION_LOCAL_NAME_CHANGED
This name is visible to remote Bluetooth devices.
Always contains the extra field EXTRA_LOCAL_NAME
containing
the name.
Requires android.Manifest.permission#BLUETOOTH
to receive.
public static final String EXTRA_LOCAL_NAME
ACTION_LOCAL_NAME_CHANGED
intents to request the local Bluetooth name.public static final String ACTION_CONNECTION_STATE_CHANGED
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.
BluetoothDevice.EXTRA_DEVICE
- The remote device.
EXTRA_CONNECTION_STATE
or EXTRA_PREVIOUS_CONNECTION_STATE
can be any of STATE_DISCONNECTED
, STATE_CONNECTING
,
STATE_CONNECTED
, STATE_DISCONNECTING
.
Requires android.Manifest.permission#BLUETOOTH
to receive.
public static final String EXTRA_CONNECTION_STATE
ACTION_CONNECTION_STATE_CHANGED
This extra represents the current connection state.public static final String EXTRA_PREVIOUS_CONNECTION_STATE
ACTION_CONNECTION_STATE_CHANGED
This extra represents the previous connection state.public static final String ACTION_BLE_STATE_CHANGED
public static final String ACTION_BLE_ACL_CONNECTED
BluetoothDevice.ACTION_ACL_CONNECTED
which
works in Bluetooth state STATE_ONpublic static final String ACTION_BLE_ACL_DISCONNECTED
BluetoothDevice.ACTION_ACL_DISCONNECTED
which
works in Bluetooth state STATE_ONpublic static final int STATE_DISCONNECTED
public static final int STATE_CONNECTING
public static final int STATE_CONNECTED
public static final int STATE_DISCONNECTING
public static final String BLUETOOTH_MANAGER_SERVICE
public static final int SOCKET_CHANNEL_AUTO_STATIC_NO_SDP
public static BluetoothAdapter getDefaultAdapter()
Currently Android only supports one Bluetooth adapter, but the API could be extended to support more. This will always return the default adapter.
public BluetoothDevice getRemoteDevice(String address)
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(java.lang.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.
address
- valid Bluetooth MAC addressIllegalArgumentException
- if address is invalidpublic BluetoothDevice getRemoteDevice(byte[] address)
BluetoothDevice
object for the given Bluetooth hardware
address.
Valid Bluetooth hardware addresses must be 6 bytes. This method expects the address in network byte order (MSB first).
A BluetoothDevice
will always be returned for a valid
hardware address, even if this adapter has never seen that device.
address
- Bluetooth MAC address (6 bytes)IllegalArgumentException
- if address is invalidpublic BluetoothLeAdvertiser getBluetoothLeAdvertiser()
BluetoothLeAdvertiser
object for Bluetooth LE Advertising operations.
Will return null if Bluetooth is turned off or if Bluetooth LE Advertising is not
supported on this device.
Use isMultipleAdvertisementSupported()
to check whether LE Advertising is supported
on this device before calling this method.
public BluetoothLeScanner getBluetoothLeScanner()
BluetoothLeScanner
object for Bluetooth LE scan operations.public boolean isEnabled()
Equivalent to:
getBluetoothState() == STATE_ON
Requires android.Manifest.permission#BLUETOOTH
public boolean isLeEnabled()
This returns true if current state is either STATE_ON or STATE_BLE_ON
public boolean disableBLE()
If the internal Adapter state is STATE_BLE_ON, this would trigger the transition to STATE_OFF and completely shut-down Bluetooth
If the Adapter state is STATE_ON, This would unregister the existance of special Bluetooth LE application and hence the further turning off of Bluetooth from UI would ensure the complete turn-off of Bluetooth rather than staying back BLE only state
This is an asynchronous call: it will return immediately, and
clients should listen for ACTION_BLE_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_BLE_ON
or STATE_OFF
based on the existance of the further Always BLE ON enabled applications
If this call returns false then there was an
immediate problem that will prevent the QAdapter from being turned off -
such as the QAadapter already being turned off.
public boolean enableBLE()
Invoking EnableBLE when Bluetooth is already in ON state, would just registers the existance of special Application and doesn't do anything to current BT state. when user turn OFF Bluetooth from UI, if there is an existance of special app, Bluetooth would stay in BLE_ON state so that LE features are still acessible to the special Applications.
This is an asynchronous call: it will return immediately, and
clients should listen for ACTION_BLE_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_BLE_TURNING_ON
, and some time
later transition to either STATE_OFF
or STATE_BLE_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.
(@link #ACTION_BLE_STATE_CHANGED) returns the Bluetooth Adapter's various
states, It includes all the classic Bluetooth Adapter states along with
internal BLE only states
public int getState()
Possible return values are
STATE_OFF
,
STATE_TURNING_ON
,
STATE_ON
,
STATE_TURNING_OFF
.
Requires android.Manifest.permission#BLUETOOTH
public int getLeState()
This returns current internal state of Adapter including LE ON/OFF
Possible return values are
STATE_OFF
,
STATE_BLE_TURNING_ON
,
STATE_BLE_ON
,
STATE_TURNING_ON
,
STATE_ON
,
STATE_TURNING_OFF
,
STATE_BLE_TURNING_OFF
.
Requires android.Manifest.permission#BLUETOOTH
public boolean enable()
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 the ACTION_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 android.Manifest.permission#BLUETOOTH_ADMIN
permission
public boolean disable()
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 android.Manifest.permission#BLUETOOTH_ADMIN
permission
public boolean disable(boolean persist)
Requires the android.Manifest.permission#BLUETOOTH_ADMIN
permission
public String getAddress()
For example, "00:11:22:AA:BB:CC".
Requires android.Manifest.permission#BLUETOOTH
public String getName()
This name is visible to remote Bluetooth devices.
Requires android.Manifest.permission#BLUETOOTH
public boolean configHciSnoopLog(boolean enable)
Requires the android.Manifest.permission#BLUETOOTH_ADMIN
permission
public boolean factoryReset()
Requires the android.Manifest.permission#BLUETOOTH_PRIVILEGED
permission
public ParcelUuid[] getUuids()
Requires android.Manifest.permission#BLUETOOTH
public boolean setName(String name)
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 android.Manifest.permission#BLUETOOTH_ADMIN
name
- a valid Bluetooth namepublic int getScanMode()
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_DISCOVERABLE
.
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 android.Manifest.permission#BLUETOOTH
public boolean setScanMode(int mode, int duration)
The Bluetooth scan mode determines if the local adapter is connectable and/or discoverable from remote Bluetooth devices.
For privacy reasons, discoverable mode is automatically turned off
after duration
seconds. For example, 120 seconds should be
enough for a remote device to initiate and complete its discovery
process.
Valid scan mode values are:
SCAN_MODE_NONE
,
SCAN_MODE_CONNECTABLE
,
SCAN_MODE_CONNECTABLE_DISCOVERABLE
.
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 android.Manifest.permission#WRITE_SECURE_SETTINGS
Applications cannot set the scan mode. They should use
startActivityForResult(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE})
instead.
mode
- valid scan modeduration
- time in seconds to apply scan mode, only used for
SCAN_MODE_CONNECTABLE_DISCOVERABLE
public boolean setScanMode(int mode)
public int getDiscoverableTimeout()
public void setDiscoverableTimeout(int timeout)
public boolean startDiscovery()
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 BluetoothDevice.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 android.Manifest.permission#BLUETOOTH_ADMIN
.
public boolean cancelDiscovery()
Requires android.Manifest.permission#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 BluetoothSocket.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.
public boolean isDiscovering()
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 android.Manifest.permission#BLUETOOTH
.
public boolean isMultipleAdvertisementSupported()
public boolean isBleScanAlwaysAvailable()
true
if BLE scan is always available, false
otherwise.
If this returns true
, application can issue BluetoothLeScanner.startScan(android.bluetooth.le.ScanCallback)
and
fetch scan results even when Bluetooth is turned off.
To change this setting, use ACTION_REQUEST_BLE_SCAN_ALWAYS_AVAILABLE
.
public boolean isPeripheralModeSupported()
public boolean isOffloadedFilteringSupported()
public boolean isOffloadedScanBatchingSupported()
public boolean isHardwareTrackingFiltersAvailable()
@Deprecated public BluetoothActivityEnergyInfo getControllerActivityEnergyInfo(int updateType)
requestControllerActivityEnergyInfo(ResultReceiver)
instead.BluetoothActivityEnergyInfo
object that
has the activity and energy info. This can be used to ascertain what
the controller has been up to, since the last sample.updateType
- Type of info, cached vs refreshed.BluetoothActivityEnergyInfo
or null if
report is unavailable or unsupportedpublic void requestControllerActivityEnergyInfo(ResultReceiver result)
BluetoothActivityEnergyInfo
object that
has the activity and energy info. This can be used to ascertain what
the controller has been up to, since the last sample.
A null value for the activity info object may be sent if the bluetooth service is
unreachable or the device does not support reporting such information.result
- The callback to which to send the activity info.public Set<BluetoothDevice> getBondedDevices()
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 android.Manifest.permission#BLUETOOTH
.
BluetoothDevice
, or null on errorpublic int getConnectionState()
Use this function along with ACTION_CONNECTION_STATE_CHANGED
intent to get the connection state of the adapter.
STATE_CONNECTED
, STATE_DISCONNECTED
,
STATE_CONNECTING
or STATE_DISCONNECTED
public int getProfileConnectionState(int profile)
BluetoothProfile.HEALTH
, BluetoothProfile.HEADSET
,
BluetoothProfile.A2DP
.
Requires android.Manifest.permission#BLUETOOTH
.
Return value can be one of
BluetoothProfile.STATE_DISCONNECTED
,
BluetoothProfile.STATE_CONNECTING
,
BluetoothProfile.STATE_CONNECTED
,
BluetoothProfile.STATE_DISCONNECTING
public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException
A remote device connecting to this socket will be authenticated and communication on this socket will be encrypted.
Use BluetoothServerSocket.accept()
to retrieve incoming
connections from a listening BluetoothServerSocket
.
Valid RFCOMM channels are in range 1 to 30.
Requires android.Manifest.permission#BLUETOOTH_ADMIN
channel
- RFCOMM channel to listen onIOException
- on error, for example Bluetooth not available, or
insufficient permissions, or channel in use.public BluetoothServerSocket listenUsingRfcommOn(int channel, boolean mitm, boolean min16DigitPin) throws IOException
A remote device connecting to this socket will be authenticated and communication on this socket will be encrypted.
Use BluetoothServerSocket.accept()
to retrieve incoming
connections from a listening BluetoothServerSocket
.
Valid RFCOMM channels are in range 1 to 30.
Requires android.Manifest.permission#BLUETOOTH_ADMIN
To auto assign a channel without creating a SDP record use
SOCKET_CHANNEL_AUTO_STATIC_NO_SDP
as channel number.
channel
- RFCOMM channel to listen onmitm
- enforce man-in-the-middle protection for authentication.min16DigitPin
- enforce a pin key length og minimum 16 digit for sec mode 2 connections.IOException
- on error, for example Bluetooth not available, or
insufficient permissions, or channel in use.public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid) throws IOException
A remote device connecting to this socket will be authenticated and communication on this socket will be encrypted.
Use BluetoothServerSocket.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 BluetoothDevice.createRfcommSocketToServiceRecord(java.util.UUID)
to
connect to this socket from another device using the same UUID
.
Requires android.Manifest.permission#BLUETOOTH
name
- service name for SDP recorduuid
- uuid for SDP recordIOException
- on error, for example Bluetooth not available, or
insufficient permissions, or channel in use.public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid) throws IOException
The link key is not required to be authenticated, i.e the communication may be
vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices,
the link will be encrypted, as encryption is mandartory.
For legacy devices (pre Bluetooth 2.1 devices) the link will not
be encrypted. Use listenUsingRfcommWithServiceRecord(java.lang.String, java.util.UUID)
, if an
encrypted and authenticated communication channel is desired.
Use BluetoothServerSocket.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 BluetoothDevice.createRfcommSocketToServiceRecord(java.util.UUID)
to
connect to this socket from another device using the same UUID
.
Requires android.Manifest.permission#BLUETOOTH
name
- service name for SDP recorduuid
- uuid for SDP recordIOException
- on error, for example Bluetooth not available, or
insufficient permissions, or channel in use.public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord(String name, UUID uuid) throws IOException
The link will be encrypted, but the link key is not required to be authenticated
i.e the communication is vulnerable to Man In the Middle attacks. Use
listenUsingRfcommWithServiceRecord(java.lang.String, java.util.UUID)
, to ensure an authenticated link key.
Use this socket if authentication of link key is not possible.
For example, for Bluetooth 2.1 devices, if any of the devices does not have
an input and output capability or just has the ability to display a numeric key,
a secure socket connection is not possible and this socket can be used.
Use listenUsingInsecureRfcommWithServiceRecord(java.lang.String, java.util.UUID)
, if encryption is not required.
For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory.
For more details, refer to the Security Model section 5.2 (vol 3) of
Bluetooth Core Specification version 2.1 + EDR.
Use BluetoothServerSocket.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 BluetoothDevice.createRfcommSocketToServiceRecord(java.util.UUID)
to
connect to this socket from another device using the same UUID
.
Requires android.Manifest.permission#BLUETOOTH
name
- service name for SDP recorduuid
- uuid for SDP recordIOException
- on error, for example Bluetooth not available, or
insufficient permissions, or channel in use.public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException
IOException
- On error, for example Bluetooth not available, or
insufficient permissions.public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port) throws IOException
IOException
- On error, for example Bluetooth not available, or
insufficient permissions.public static BluetoothServerSocket listenUsingScoOn() throws IOException
IOException
- On error, for example Bluetooth not available, or
insufficient permissions.public BluetoothServerSocket listenUsingL2capOn(int port, boolean mitm, boolean min16DigitPin) throws IOException
To auto assign a port without creating a SDP record use
SOCKET_CHANNEL_AUTO_STATIC_NO_SDP
as port number.
port
- the PSM to listen onmitm
- enforce man-in-the-middle protection for authentication.min16DigitPin
- enforce a pin key length og minimum 16 digit for sec mode 2 connections.IOException
- On error, for example Bluetooth not available, or
insufficient permissions.public BluetoothServerSocket listenUsingL2capOn(int port) throws IOException
To auto assign a port without creating a SDP record use
SOCKET_CHANNEL_AUTO_STATIC_NO_SDP
as port number.
port
- the PSM to listen onIOException
- On error, for example Bluetooth not available, or
insufficient permissions.public Pair<byte[],byte[]> readOutOfBandData()
Requires android.Manifest.permission#BLUETOOTH
public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener, int profile)
Profile can be one of BluetoothProfile.HEALTH
, BluetoothProfile.HEADSET
,
BluetoothProfile.A2DP
, BluetoothProfile.GATT
, or
BluetoothProfile.GATT_SERVER
. Clients must implement
BluetoothProfile.ServiceListener
to get notified of
the connection status and to get the proxy object.
context
- Context of the applicationlistener
- The service Listener for connection callbacks.profile
- The Bluetooth profile; either BluetoothProfile.HEALTH
,
BluetoothProfile.HEADSET
, BluetoothProfile.A2DP
.
BluetoothProfile.GATT
or BluetoothProfile.GATT_SERVER
.public void closeProfileProxy(int profile, BluetoothProfile proxy)
Clients should call this when they are no longer using
the proxy obtained from getProfileProxy(android.content.Context, android.bluetooth.BluetoothProfile.ServiceListener, int)
.
Profile can be one of BluetoothProfile.HEALTH
, BluetoothProfile.HEADSET
or
BluetoothProfile.A2DP
profile
- proxy
- Profile proxy objectpublic boolean enableNoAutoConnect()
public boolean changeApplicationBluetoothState(boolean on, BluetoothAdapter.BluetoothStateChangeCallback callback)
Some applications need to use Bluetooth for short periods of time to transfer data but don't want all the associated implications like automatic connection to headsets etc.
Multiple applications can call this. This is reference counted and Bluetooth disabled only when no one else is using it. There will be no UI shown to the user while bluetooth is being enabled. Any user action will override this call. For example, if user wants Bluetooth on and the last user of this API wanted to disable Bluetooth, Bluetooth will not be turned off.
This API is only meant to be used by internal applications. Third
party applications but use enable()
and disable()
APIs.
If this API returns true, it means the callback will be called. The callback will be called with the current state of Bluetooth. If the state is not what was requested, an internal error would be the reason. If Bluetooth is already on and if this function is called to turn it on, the api will return true and a callback will be called.
Requires android.Manifest.permission#BLUETOOTH
on
- True for on, false for off.callback
- The callback to notify changes to the state.protected void finalize() throws Throwable
Object
finalize
method to dispose of
system resources or to perform other cleanup.
The general contract of finalize
is that it is invoked
if and when the JavaTM virtual
machine has determined that there is no longer any
means by which this object can be accessed by any thread that has
not yet died, except as a result of an action taken by the
finalization of some other object or class which is ready to be
finalized. The finalize
method may take any action, including
making this object available again to other threads; the usual purpose
of finalize
, however, is to perform cleanup actions before
the object is irrevocably discarded. For example, the finalize method
for an object that represents an input/output connection might perform
explicit I/O transactions to break the connection before the object is
permanently discarded.
The finalize
method of class Object
performs no
special action; it simply returns normally. Subclasses of
Object
may override this definition.
The Java programming language does not guarantee which thread will
invoke the finalize
method for any given object. It is
guaranteed, however, that the thread that invokes finalize will not
be holding any user-visible synchronization locks when finalize is
invoked. If an uncaught exception is thrown by the finalize method,
the exception is ignored and finalization of that object terminates.
After the finalize
method has been invoked for an object, no
further action is taken until the Java virtual machine has again
determined that there is no longer any means by which this object can
be accessed by any thread that has not yet died, including possible
actions by other objects or classes which are ready to be finalized,
at which point the object may be discarded.
The finalize
method is never invoked more than once by a Java
virtual machine for any given object.
Any exception thrown by the finalize
method causes
the finalization of this object to be halted, but is otherwise
ignored.
public static boolean checkBluetoothAddress(String address)
Alphabetic characters must be uppercase to be valid.
address
- Bluetooth address as string@Deprecated public boolean startLeScan(BluetoothAdapter.LeScanCallback callback)
BluetoothLeScanner.startScan(List, ScanSettings, ScanCallback)
instead.Results of the scan are reported using the
BluetoothAdapter.LeScanCallback.onLeScan(android.bluetooth.BluetoothDevice, int, byte[])
callback.
Requires android.Manifest.permission#BLUETOOTH_ADMIN
permission.
callback
- the callback LE scan results are delivered@Deprecated public boolean startLeScan(UUID[] serviceUuids, BluetoothAdapter.LeScanCallback callback)
BluetoothLeScanner.startScan(List, ScanSettings, ScanCallback)
instead.Devices which advertise all specified services are reported using the
BluetoothAdapter.LeScanCallback.onLeScan(android.bluetooth.BluetoothDevice, int, byte[])
callback.
Requires android.Manifest.permission#BLUETOOTH_ADMIN
permission.
serviceUuids
- Array of services to look forcallback
- the callback LE scan results are delivered@Deprecated public void stopLeScan(BluetoothAdapter.LeScanCallback callback)
BluetoothLeScanner.stopScan(ScanCallback)
instead.Requires android.Manifest.permission#BLUETOOTH_ADMIN
permission.
callback
- used to identify which scan to stop
must be the same handle used to start the scan