FileDocCategorySizeDatePackage
BluetoothDevice.javaAPI DocAndroid 5.1 API54246Thu Mar 12 22:22:10 GMT 2015android.bluetooth

BluetoothDevice

public final class BluetoothDevice extends Object implements android.os.Parcelable
Represents a remote Bluetooth device. A {@link BluetoothDevice} lets you create a connection with the respective device or query information about it, such as the name, address, class, and bonding state.

This class is really just a thin wrapper for a Bluetooth hardware address. Objects of this class are immutable. Operations on this class are performed on the remote Bluetooth hardware address, using the {@link BluetoothAdapter} that was used to create this {@link BluetoothDevice}.

To get a {@link BluetoothDevice}, use {@link BluetoothAdapter#getRemoteDevice(String) BluetoothAdapter.getRemoteDevice(String)} to create one representing a device of a known MAC address (which you can get through device discovery with {@link BluetoothAdapter}) or get one from the set of bonded devices returned by {@link BluetoothAdapter#getBondedDevices() BluetoothAdapter.getBondedDevices()}. You can then open a {@link BluetoothSocket} for communication with the remote device, using {@link #createRfcommSocketToServiceRecord(UUID)}.

Note: Requires the {@link android.Manifest.permission#BLUETOOTH} permission.

Developer Guides

For more information about using Bluetooth, read the Bluetooth developer guide.

{@see BluetoothAdapter} {@see BluetoothSocket}

Fields Summary
private static final String
TAG
private static final boolean
DBG
private static final int
CONNECTION_STATE_DISCONNECTED
Connection state bitmask as returned by getConnectionState.
private static final int
CONNECTION_STATE_CONNECTED
private static final int
CONNECTION_STATE_ENCRYPTED_BREDR
private static final int
CONNECTION_STATE_ENCRYPTED_LE
public static final int
ERROR
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(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)

public static final String
ACTION_FOUND
Broadcast Action: Remote device discovered.

Sent when a remote device is found during discovery.

Always contains the extra fields {@link #EXTRA_DEVICE} and {@link #EXTRA_CLASS}. Can contain the extra fields {@link #EXTRA_NAME} and/or {@link #EXTRA_RSSI} if they are available.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
ACTION_DISAPPEARED
Broadcast Action: Remote device disappeared.

Sent when a remote device that was found in the last discovery is not found in the current discovery.

Always contains the extra field {@link #EXTRA_DEVICE}.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
ACTION_CLASS_CHANGED
Broadcast Action: Bluetooth class of a remote device has changed.

Always contains the extra fields {@link #EXTRA_DEVICE} and {@link #EXTRA_CLASS}.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive. {@see BluetoothClass}

public static final String
ACTION_ACL_CONNECTED
Broadcast Action: Indicates a low level (ACL) connection has been established with a remote device.

Always contains the extra field {@link #EXTRA_DEVICE}.

ACL connections are managed automatically by the Android Bluetooth stack.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
ACTION_ACL_DISCONNECT_REQUESTED
Broadcast Action: Indicates that a low level (ACL) disconnection has been requested for a remote device, and it will soon be disconnected.

This is useful for graceful disconnection. Applications should use this intent as a hint to immediately terminate higher level connections (RFCOMM, L2CAP, or profile connections) to the remote device.

Always contains the extra field {@link #EXTRA_DEVICE}.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
ACTION_ACL_DISCONNECTED
Broadcast Action: Indicates a low level (ACL) disconnection from a remote device.

Always contains the extra field {@link #EXTRA_DEVICE}.

ACL connections are managed automatically by the Android Bluetooth stack.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
ACTION_NAME_CHANGED
Broadcast Action: Indicates the friendly name of a remote device has been retrieved for the first time, or changed since the last retrieval.

Always contains the extra fields {@link #EXTRA_DEVICE} and {@link #EXTRA_NAME}.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
ACTION_ALIAS_CHANGED
Broadcast Action: Indicates the alias of a remote device has been changed.

Always contains the extra field {@link #EXTRA_DEVICE}.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
ACTION_BOND_STATE_CHANGED
Broadcast Action: Indicates a change in the bond state of a remote device. For example, if a device is bonded (paired).

Always contains the extra fields {@link #EXTRA_DEVICE}, {@link #EXTRA_BOND_STATE} and {@link #EXTRA_PREVIOUS_BOND_STATE}.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
EXTRA_DEVICE
Used as a Parcelable {@link BluetoothDevice} extra field in every intent broadcast by this class. It contains the {@link BluetoothDevice} that the intent applies to.
public static final String
EXTRA_NAME
Used as a String extra field in {@link #ACTION_NAME_CHANGED} and {@link #ACTION_FOUND} intents. It contains the friendly Bluetooth name.
public static final String
EXTRA_RSSI
Used as an optional short extra field in {@link #ACTION_FOUND} intents. Contains the RSSI value of the remote device as reported by the Bluetooth hardware.
public static final String
EXTRA_CLASS
Used as a Parcelable {@link BluetoothClass} extra field in {@link #ACTION_FOUND} and {@link #ACTION_CLASS_CHANGED} intents.
public static final String
EXTRA_BOND_STATE
Used as an int extra field in {@link #ACTION_BOND_STATE_CHANGED} intents. Contains the bond state of the remote device.

Possible values are: {@link #BOND_NONE}, {@link #BOND_BONDING}, {@link #BOND_BONDED}.

public static final String
EXTRA_PREVIOUS_BOND_STATE
Used as an int extra field in {@link #ACTION_BOND_STATE_CHANGED} intents. Contains the previous bond state of the remote device.

Possible values are: {@link #BOND_NONE}, {@link #BOND_BONDING}, {@link #BOND_BONDED}.

public static final int
BOND_NONE
Indicates the remote device is not bonded (paired).

There is no shared link key with the remote device, so communication (if it is allowed at all) will be unauthenticated and unencrypted.

public static final int
BOND_BONDING
Indicates bonding (pairing) is in progress with the remote device.
public static final int
BOND_BONDED
Indicates the remote device is bonded (paired).

A shared link keys exists locally for the remote device, so communication can be authenticated and encrypted.

Being bonded (paired) with a remote device does not necessarily mean the device is currently connected. It just means that the pending procedure was completed at some earlier time, and the link key is still stored locally, ready to use on the next connection.

public static final String
EXTRA_REASON
Used as an int extra field in {@link #ACTION_PAIRING_REQUEST} intents for unbond reason.
public static final String
EXTRA_PAIRING_VARIANT
Used as an int extra field in {@link #ACTION_PAIRING_REQUEST} intents to indicate pairing method used. Possible values are: {@link #PAIRING_VARIANT_PIN}, {@link #PAIRING_VARIANT_PASSKEY_CONFIRMATION},
public static final String
EXTRA_PAIRING_KEY
Used as an int extra field in {@link #ACTION_PAIRING_REQUEST} intents as the value of passkey.
public static final int
DEVICE_TYPE_UNKNOWN
Bluetooth device type, Unknown
public static final int
DEVICE_TYPE_CLASSIC
Bluetooth device type, Classic - BR/EDR devices
public static final int
DEVICE_TYPE_LE
Bluetooth device type, Low Energy - LE-only
public static final int
DEVICE_TYPE_DUAL
Bluetooth device type, Dual Mode - BR/EDR/LE
public static final String
ACTION_UUID
Broadcast Action: This intent is used to broadcast the {@link UUID} wrapped as a {@link android.os.ParcelUuid} of the remote device after it has been fetched. This intent is sent only when the UUIDs of the remote device are requested to be fetched using Service Discovery Protocol

Always contains the extra field {@link #EXTRA_DEVICE}

Always contains the extra field {@link #EXTRA_UUID}

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
ACTION_MAS_INSTANCE
public static final String
ACTION_NAME_FAILED
Broadcast Action: Indicates a failure to retrieve the name of a remote device.

Always contains the extra field {@link #EXTRA_DEVICE}.

Requires {@link android.Manifest.permission#BLUETOOTH} to receive.

public static final String
ACTION_PAIRING_REQUEST
Broadcast Action: This intent is used to broadcast PAIRING REQUEST

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} to receive.

public static final String
ACTION_PAIRING_CANCEL
public static final String
ACTION_CONNECTION_ACCESS_REQUEST
public static final String
ACTION_CONNECTION_ACCESS_REPLY
public static final String
ACTION_CONNECTION_ACCESS_CANCEL
public static final String
EXTRA_ACCESS_REQUEST_TYPE
Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REQUEST} intent.
public static final int
REQUEST_TYPE_PROFILE_CONNECTION
public static final int
REQUEST_TYPE_PHONEBOOK_ACCESS
public static final int
REQUEST_TYPE_MESSAGE_ACCESS
public static final String
EXTRA_PACKAGE_NAME
Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REQUEST} intents, Contains package name to return reply intent to.
public static final String
EXTRA_CLASS_NAME
Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REQUEST} intents, Contains class name to return reply intent to.
public static final String
EXTRA_CONNECTION_ACCESS_RESULT
Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REPLY} intent.
public static final int
CONNECTION_ACCESS_YES
public static final int
CONNECTION_ACCESS_NO
public static final String
EXTRA_ALWAYS_ALLOWED
Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REPLY} intents, Contains boolean to indicate if the allowed response is once-for-all so that next request will be granted without asking user again.
public static final int
BOND_SUCCESS
A bond attempt succeeded
public static final int
UNBOND_REASON_AUTH_FAILED
A bond attempt failed because pins did not match, or remote device did not respond to pin request in time
public static final int
UNBOND_REASON_AUTH_REJECTED
A bond attempt failed because the other side explicitly rejected bonding
public static final int
UNBOND_REASON_AUTH_CANCELED
A bond attempt failed because we canceled the bonding process
public static final int
UNBOND_REASON_REMOTE_DEVICE_DOWN
A bond attempt failed because we could not contact the remote device
public static final int
UNBOND_REASON_DISCOVERY_IN_PROGRESS
A bond attempt failed because a discovery is in progress
public static final int
UNBOND_REASON_AUTH_TIMEOUT
A bond attempt failed because of authentication timeout
public static final int
UNBOND_REASON_REPEATED_ATTEMPTS
A bond attempt failed because of repeated attempts
public static final int
UNBOND_REASON_REMOTE_AUTH_CANCELED
A bond attempt failed because we received an Authentication Cancel by remote end
public static final int
UNBOND_REASON_REMOVED
An existing bond was explicitly revoked
public static final int
PAIRING_VARIANT_PIN
The user will be prompted to enter a pin or an app will enter a pin for user.
public static final int
PAIRING_VARIANT_PASSKEY
The user will be prompted to enter a passkey
public static final int
PAIRING_VARIANT_PASSKEY_CONFIRMATION
The user will be prompted to confirm the passkey displayed on the screen or an app will confirm the passkey for the user.
public static final int
PAIRING_VARIANT_CONSENT
The user will be prompted to accept or deny the incoming pairing request
public static final int
PAIRING_VARIANT_DISPLAY_PASSKEY
The user will be prompted to enter the passkey displayed on remote device This is used for Bluetooth 2.1 pairing.
public static final int
PAIRING_VARIANT_DISPLAY_PIN
The user will be prompted to enter the PIN displayed on remote device. This is used for Bluetooth 2.0 pairing.
public static final int
PAIRING_VARIANT_OOB_CONSENT
The user will be prompted to accept or deny the OOB pairing request
public static final String
EXTRA_UUID
Used as an extra field in {@link #ACTION_UUID} intents, Contains the {@link android.os.ParcelUuid}s of the remote device which is a parcelable version of {@link UUID}.
public static final int
ACCESS_UNKNOWN
For {@link #getPhonebookAccessPermission}, {@link #setPhonebookAccessPermission}, {@link #getMessageAccessPermission} and {@link #setMessageAccessPermission}.
public static final int
ACCESS_ALLOWED
For {@link #getPhonebookAccessPermission}, {@link #setPhonebookAccessPermission}, {@link #getMessageAccessPermission} and {@link #setMessageAccessPermission}.
public static final int
ACCESS_REJECTED
For {@link #getPhonebookAccessPermission}, {@link #setPhonebookAccessPermission}, {@link #getMessageAccessPermission} and {@link #setMessageAccessPermission}.
public static final int
TRANSPORT_AUTO
No preferrence of physical transport for GATT connections to remote dual-mode devices
public static final int
TRANSPORT_BREDR
Prefer BR/EDR transport for GATT connections to remote dual-mode devices
public static final int
TRANSPORT_LE
Prefer LE transport for GATT connections to remote dual-mode devices
public static final String
EXTRA_MAS_INSTANCE
private static IBluetooth
sService
Lazy initialization. Guaranteed final after first object constructed, or getService() called. TODO: Unify implementation of sService amongst BluetoothFoo API's
private final String
mAddress
static IBluetoothManagerCallback
mStateChangeCallback
public static final Parcelable.Creator
CREATOR
Constructors Summary
BluetoothDevice(String address)
Create a new BluetoothDevice Bluetooth MAC address must be upper case, such as "00:11:22:33:AA:BB", and is validated in this constructor.

param
address valid Bluetooth MAC address
throws
RuntimeException Bluetooth is not available on this platform
throws
IllegalArgumentException address is invalid
hide

                                                  
    /*package*/   
        getService();  // ensures sService is initialized
        if (!BluetoothAdapter.checkBluetoothAddress(address)) {
            throw new IllegalArgumentException(address + " is not a valid Bluetooth address");
        }

        mAddress = address;
    
Methods Summary
public booleancancelBondProcess()
Cancel an in-progress bonding request started with {@link #createBond}.

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.

return
true on success, false on error
hide

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot cancel Remote Device bond");
            return false;
        }
        try {
            return sService.cancelBondProcess(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    
public booleancancelPairingUserInput()

hide

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot create pairing user input");
            return false;
        }
        try {
            return sService.cancelBondProcess(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    
public BluetoothGattconnectGatt(android.content.Context context, boolean autoConnect, BluetoothGattCallback callback)
Connect to GATT Server hosted by this device. Caller acts as GATT client. The callback is used to deliver results to Caller, such as connection status as well as any further GATT client operations. The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct GATT client operations.

param
callback GATT callback handler that will receive asynchronous callbacks.
param
autoConnect Whether to directly connect to the remote device (false) or to automatically connect as soon as the remote device becomes available (true).
throws
IllegalArgumentException if callback is null

        return (connectGatt(context, autoConnect,callback, TRANSPORT_AUTO));
    
public BluetoothGattconnectGatt(android.content.Context context, boolean autoConnect, BluetoothGattCallback callback, int transport)
Connect to GATT Server hosted by this device. Caller acts as GATT client. The callback is used to deliver results to Caller, such as connection status as well as any further GATT client operations. The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct GATT client operations.

param
callback GATT callback handler that will receive asynchronous callbacks.
param
autoConnect Whether to directly connect to the remote device (false) or to automatically connect as soon as the remote device becomes available (true).
param
transport preferred transport for GATT connections to remote dual-mode devices {@link BluetoothDevice#TRANSPORT_AUTO} or {@link BluetoothDevice#TRANSPORT_BREDR} or {@link BluetoothDevice#TRANSPORT_LE}
throws
IllegalArgumentException if callback is null
hide

        // TODO(Bluetooth) check whether platform support BLE
        //     Do the check here or in GattServer?
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        IBluetoothManager managerService = adapter.getBluetoothManager();
        try {
            IBluetoothGatt iGatt = managerService.getBluetoothGatt();
            if (iGatt == null) {
                // BLE is not supported
                return null;
            }
            BluetoothGatt gatt = new BluetoothGatt(context, iGatt, this, transport);
            gatt.connect(autoConnect, callback);
            return gatt;
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return null;
    
public static byte[]convertPinToBytes(java.lang.String pin)
Check that a pin is valid and convert to byte array. Bluetooth pin's are 1 to 16 bytes of UTF-8 characters.

param
pin pin as java String
return
the pin code as a UTF-8 byte array, or null if it is an invalid Bluetooth pin.
hide

        if (pin == null) {
            return null;
        }
        byte[] pinBytes;
        try {
            pinBytes = pin.getBytes("UTF-8");
        } catch (UnsupportedEncodingException uee) {
            Log.e(TAG, "UTF-8 not supported?!?");  // this should not happen
            return null;
        }
        if (pinBytes.length <= 0 || pinBytes.length > 16) {
            return null;
        }
        return pinBytes;
    
public booleancreateBond()
Start the bonding (pairing) process with the remote device.

This is an asynchronous call, it will return immediately. Register for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when the bonding process completes, and its result.

Android system services will handle the necessary user interactions to confirm and complete the bonding process.

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.

return
false on immediate error, true if bonding will begin

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot create bond to Remote Device");
            return false;
        }
        try {
            return sService.createBond(this, TRANSPORT_AUTO);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    
public booleancreateBond(int transport)
Start the bonding (pairing) process with the remote device using the specified transport.

This is an asynchronous call, it will return immediately. Register for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when the bonding process completes, and its result.

Android system services will handle the necessary user interactions to confirm and complete the bonding process.

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.

param
transport The transport to use for the pairing procedure.
return
false on immediate error, true if bonding will begin
throws
IllegalArgumentException if an invalid transport was specified
hide

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot create bond to Remote Device");
            return false;
        }
        if (TRANSPORT_AUTO > transport || transport > TRANSPORT_LE)
        {
            throw new IllegalArgumentException(transport + " is not a valid Bluetooth transport");
        }
        try {
            return sService.createBond(this, transport);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    
public booleancreateBondOutOfBand(byte[] hash, byte[] randomizer)
Start the bonding (pairing) process with the remote device using the Out Of Band mechanism.

This is an asynchronous call, it will return immediately. Register for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when the bonding process completes, and its result.

Android system services will handle the necessary user interactions to confirm and complete the bonding process.

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.

param
hash - Simple Secure pairing hash
param
randomizer - The random key obtained using OOB
return
false on immediate error, true if bonding will begin
hide

        //TODO(BT)
        /*
        try {
            return sService.createBondOutOfBand(this, hash, randomizer);
        } catch (RemoteException e) {Log.e(TAG, "", e);}*/
        return false;
    
public BluetoothSocketcreateInsecureRfcommSocket(int port)
Construct an insecure RFCOMM socket ready to start an outgoing connection. Call #connect on the returned #BluetoothSocket to begin the connection. The remote device will not be authenticated and communication on this socket will not be encrypted.

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}

param
port remote port
return
An RFCOMM BluetoothSocket
throws
IOException On error, for example Bluetooth not available, or insufficient permissions.
hide

        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, false, false, this, port,
                null);
    
public BluetoothSocketcreateInsecureRfcommSocketToServiceRecord(java.util.UUID uuid)
Create an RFCOMM {@link BluetoothSocket} socket ready to start an insecure outgoing connection to this remote device using SDP lookup of uuid.

The communication channel will not have an authenticated link key i.e it will be subject to man-in-the-middle attacks. For Bluetooth 2.1 devices, the link key will be encrypted, as encryption is mandatory. For legacy devices (pre Bluetooth 2.1 devices) the link key will be not be encrypted. Use {@link #createRfcommSocketToServiceRecord} if an encrypted and authenticated communication channel is desired.

This is designed to be used with {@link BluetoothAdapter#listenUsingInsecureRfcommWithServiceRecord} for peer-peer Bluetooth applications.

Use {@link BluetoothSocket#connect} to initiate the outgoing connection. This will also perform an SDP lookup of the given uuid to determine which channel to connect to.

The remote device will be authenticated and communication on this socket will be encrypted.

Hint: If you are connecting to a Bluetooth serial board then try using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB. However if you are connecting to an Android peer then please generate your own unique UUID.

Requires {@link android.Manifest.permission#BLUETOOTH}

param
uuid service record uuid to lookup RFCOMM channel
return
a RFCOMM BluetoothServerSocket ready for an outgoing connection
throws
IOException on error, for example Bluetooth not available, or insufficient permissions

        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, false, false, this, -1,
                new ParcelUuid(uuid));
    
public BluetoothSocketcreateRfcommSocket(int channel)
Create an RFCOMM {@link BluetoothSocket} ready to start a secure outgoing connection to this remote device on given channel.

The remote device will be authenticated and communication on this socket will be encrypted.

Use this socket only if an authenticated socket link is possible. Authentication refers to the authentication of the link key to prevent man-in-the-middle type of attacks. 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. In such a case, use {#link createInsecureRfcommSocket}. For more details, refer to the Security Model section 5.2 (vol 3) of Bluetooth Core Specification version 2.1 + EDR.

Use {@link BluetoothSocket#connect} to initiate the outgoing connection.

Valid RFCOMM channels are in range 1 to 30.

Requires {@link android.Manifest.permission#BLUETOOTH}

param
channel RFCOMM channel to connect to
return
a RFCOMM BluetoothServerSocket ready for an outgoing connection
throws
IOException on error, for example Bluetooth not available, or insufficient permissions
hide

        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, true, true, this, channel,
                null);
    
public BluetoothSocketcreateRfcommSocketToServiceRecord(java.util.UUID uuid)
Create an RFCOMM {@link BluetoothSocket} ready to start a secure outgoing connection to this remote device using SDP lookup of uuid.

This is designed to be used with {@link BluetoothAdapter#listenUsingRfcommWithServiceRecord} for peer-peer Bluetooth applications.

Use {@link BluetoothSocket#connect} to initiate the outgoing connection. This will also perform an SDP lookup of the given uuid to determine which channel to connect to.

The remote device will be authenticated and communication on this socket will be encrypted.

Use this socket only if an authenticated socket link is possible. Authentication refers to the authentication of the link key to prevent man-in-the-middle type of attacks. 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. In such a case, use {#link createInsecureRfcommSocketToServiceRecord}. For more details, refer to the Security Model section 5.2 (vol 3) of Bluetooth Core Specification version 2.1 + EDR.

Hint: If you are connecting to a Bluetooth serial board then try using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB. However if you are connecting to an Android peer then please generate your own unique UUID.

Requires {@link android.Manifest.permission#BLUETOOTH}

param
uuid service record uuid to lookup RFCOMM channel
return
a RFCOMM BluetoothServerSocket ready for an outgoing connection
throws
IOException on error, for example Bluetooth not available, or insufficient permissions

        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, true, true, this, -1,
                new ParcelUuid(uuid));
    
public BluetoothSocketcreateScoSocket()
Construct a SCO socket ready to start an outgoing connection. Call #connect on the returned #BluetoothSocket to begin the connection.

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}

return
a SCO BluetoothSocket
throws
IOException on error, for example Bluetooth not available, or insufficient permissions.
hide

        return new BluetoothSocket(BluetoothSocket.TYPE_SCO, -1, true, true, this, -1, null);
    
public intdescribeContents()

        return 0;
    
public booleanequals(java.lang.Object o)

        if (o instanceof BluetoothDevice) {
            return mAddress.equals(((BluetoothDevice)o).getAddress());
        }
        return false;
    
public booleanfetchMasInstances()

hide

         if (sService == null) {
             Log.e(TAG, "BT not enabled. Cannot query remote device for MAS instances");
             return false;
         }
         try {
             return sService.fetchRemoteMasInstances(this);
         } catch (RemoteException e) {Log.e(TAG, "", e);}
         return false;
     
public booleanfetchUuidsWithSdp()
Perform a service discovery on the remote device to get the UUIDs supported.

This API is asynchronous and {@link #ACTION_UUID} intent is sent, with the UUIDs supported by the remote end. If there is an error in getting the SDP records or if the process takes a long time, {@link #ACTION_UUID} intent is sent with the UUIDs that is currently present in the cache. Clients should use the {@link #getUuids} to get UUIDs if service discovery is not to be performed.

Requires {@link android.Manifest.permission#BLUETOOTH}.

return
False if the sanity check fails, True if the process of initiating an ACL connection to the remote device was started.

        IBluetooth service = sService;
        if (service == null) {
            Log.e(TAG, "BT not enabled. Cannot fetchUuidsWithSdp");
            return false;
        }
        try {
            return service.fetchRemoteUuids(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
            return false;
    
public java.lang.StringgetAddress()
Returns the hardware address of this BluetoothDevice.

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

return
Bluetooth hardware address as string

        if (DBG) Log.d(TAG, "mAddress: " + mAddress);
        return mAddress;
    
public java.lang.StringgetAlias()
Get the Bluetooth alias of the remote device.

Alias is the locally modified name of a remote device.

return
the Bluetooth alias, or null if no alias or there was a problem
hide

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot get Remote Device Alias");
            return null;
        }
        try {
            return sService.getRemoteAlias(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return null;
    
public java.lang.StringgetAliasName()
Get the Bluetooth alias of the remote device. If Alias is null, get the Bluetooth name instead.

see
#getAlias()
see
#getName()
return
the Bluetooth alias, or null if no alias or there was a problem
hide

        String name = getAlias();
        if (name == null) {
            name = getName();
        }
        return name;
    
public BluetoothClassgetBluetoothClass()
Get the Bluetooth class of the remote device.

Requires {@link android.Manifest.permission#BLUETOOTH}.

return
Bluetooth class object, or null on error

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot get Bluetooth Class");
            return null;
        }
        try {
            int classInt = sService.getRemoteClass(this);
            if (classInt == BluetoothClass.ERROR) return null;
            return new BluetoothClass(classInt);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return null;
    
public intgetBondState()
Get the bond state of the remote device.

Possible values for the bond state are: {@link #BOND_NONE}, {@link #BOND_BONDING}, {@link #BOND_BONDED}.

Requires {@link android.Manifest.permission#BLUETOOTH}.

return
the bond state

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot get bond state");
            return BOND_NONE;
        }
        try {
            return sService.getBondState(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        catch (NullPointerException npe) {
            // Handle case where bluetooth service proxy
            // is already null.
            Log.e(TAG, "NullPointerException for getBondState() of device ("+
                getAddress()+")", npe);
        }
        return BOND_NONE;
    
public intgetMessageAccessPermission()
Requires {@link android.Manifest.permission#BLUETOOTH}.

return
Whether the message access is allowed to this device. Can be {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or {@link #ACCESS_REJECTED}.
hide

        if (sService == null) {
            return ACCESS_UNKNOWN;
        }
        try {
            return sService.getMessageAccessPermission(this);
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
        }
        return ACCESS_UNKNOWN;
    
public java.lang.StringgetName()
Get the friendly Bluetooth name of the remote device.

The local adapter will automatically retrieve remote names when performing a device scan, and will cache them. This method just returns the name for this device from the cache.

Requires {@link android.Manifest.permission#BLUETOOTH}

return
the Bluetooth name, or null if there was a problem.

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot get Remote Device name");
            return null;
        }
        try {
            return sService.getRemoteName(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return null;
    
public intgetPhonebookAccessPermission()
Requires {@link android.Manifest.permission#BLUETOOTH}.

return
Whether the phonebook access is allowed to this device. Can be {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or {@link #ACCESS_REJECTED}.
hide

        if (sService == null) {
            return ACCESS_UNKNOWN;
        }
        try {
            return sService.getPhonebookAccessPermission(this);
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
        }
        return ACCESS_UNKNOWN;
    
static IBluetoothgetService()


    /*package*/    
        synchronized (BluetoothDevice.class) {
            if (sService == null) {
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                sService = adapter.getBluetoothService(mStateChangeCallback);
            }
        }
        return sService;
    
public intgetServiceChannel(android.os.ParcelUuid uuid)

hide

        //TODO(BT)
        /*
         try {
             return sService.getRemoteServiceChannel(this, uuid);
         } catch (RemoteException e) {Log.e(TAG, "", e);}*/
         return BluetoothDevice.ERROR;
    
public intgetType()
Get the Bluetooth device type of the remote device.

Requires {@link android.Manifest.permission#BLUETOOTH}

return
the device type {@link #DEVICE_TYPE_CLASSIC}, {@link #DEVICE_TYPE_LE} {@link #DEVICE_TYPE_DUAL}. {@link #DEVICE_TYPE_UNKNOWN} if it's not available

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot get Remote Device type");
            return DEVICE_TYPE_UNKNOWN;
        }
        try {
            return sService.getRemoteType(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return DEVICE_TYPE_UNKNOWN;
    
public android.os.ParcelUuid[]getUuids()
Returns the supported features (UUIDs) of the remote device.

This method does not start a service discovery procedure to retrieve the UUIDs from the remote device. Instead, the local cached copy of the service UUIDs are returned.

Use {@link #fetchUuidsWithSdp} if fresh UUIDs are desired.

Requires {@link android.Manifest.permission#BLUETOOTH}.

return
the supported features (UUIDs) of the remote device, or null on error

         if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot get remote device Uuids");
             return null;
         }
        try {
            return sService.getRemoteUuids(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return null;
    
public inthashCode()

        return mAddress.hashCode();
    
public booleanisBluetoothDock()

hide

        // TODO(BT)
        /*
        try {
            return sService.isBluetoothDock(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}*/
        return false;
    
public booleanisConnected()
Returns whether there is an open connection to this device.

Requires {@link android.Manifest.permission#BLUETOOTH}.

return
True if there is at least one open connection to this device.
hide

        if (sService == null) {
            // BT is not enabled, we cannot be connected.
            return false;
        }
        try {
            return sService.getConnectionState(this) != CONNECTION_STATE_DISCONNECTED;
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
            return false;
        }
    
public booleanisEncrypted()
Returns whether there is an open connection to this device that has been encrypted.

Requires {@link android.Manifest.permission#BLUETOOTH}.

return
True if there is at least one encrypted connection to this device.
hide

        if (sService == null) {
            // BT is not enabled, we cannot be connected.
            return false;
        }
        try {
            return sService.getConnectionState(this) > CONNECTION_STATE_CONNECTED;
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
            return false;
        }
    
public booleanremoveBond()
Remove bond (pairing) with the remote device.

Delete the link key associated with the remote device, and immediately terminate connections to that device that require authentication and encryption.

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.

return
true on success, false on error
hide

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot remove Remote Device bond");
            return false;
        }
        try {
            return sService.removeBond(this);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    
public booleansetAlias(java.lang.String alias)
Set the Bluetooth alias of the remote device.

Alias is the locally modified name of a remote device.

This methoid overwrites the alias. The changed alias is saved in the local storage so that the change is preserved over power cycle.

return
true on success, false on error
hide

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot set Remote Device name");
            return false;
        }
        try {
            return sService.setRemoteAlias(this, alias);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    
public booleansetDeviceOutOfBandData(byte[] hash, byte[] randomizer)
Set the Out Of Band data for a remote device to be used later in the pairing mechanism. Users can obtain this data through other trusted channels

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.

param
hash Simple Secure pairing hash
param
randomizer The random key obtained using OOB
return
false on error; true otherwise
hide

      //TODO(BT)
      /*
      try {
        return sService.setDeviceOutOfBandData(this, hash, randomizer);
      } catch (RemoteException e) {Log.e(TAG, "", e);} */
      return false;
    
public booleansetMessageAccessPermission(int value)
Sets whether the message access is allowed to this device.

Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}.

param
value Can be {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or {@link #ACCESS_REJECTED}.
return
Whether the value has been successfully set.
hide

        if (sService == null) {
            return false;
        }
        try {
            return sService.setMessageAccessPermission(this, value);
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
        }
        return false;
    
public booleansetPairingConfirmation(boolean confirm)
Confirm passkey for {@link #PAIRING_VARIANT_PASSKEY_CONFIRMATION} pairing.

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.

return
true confirmation has been sent out false for error

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot set pairing confirmation");
            return false;
        }
        try {
            return sService.setPairingConfirmation(this, confirm);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    
public booleansetPasskey(int passkey)

hide

        //TODO(BT)
        /*
        try {
            return sService.setPasskey(this, true, 4, passkey);
        } catch (RemoteException e) {Log.e(TAG, "", e);}*/
        return false;
    
public booleansetPhonebookAccessPermission(int value)
Sets whether the phonebook access is allowed to this device.

Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}.

param
value Can be {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or {@link #ACCESS_REJECTED}.
return
Whether the value has been successfully set.
hide

        if (sService == null) {
            return false;
        }
        try {
            return sService.setPhonebookAccessPermission(this, value);
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
        }
        return false;
    
public booleansetPin(byte[] pin)
Set the pin during pairing when the pairing method is {@link #PAIRING_VARIANT_PIN}

Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.

return
true pin has been set false for error

        if (sService == null) {
            Log.e(TAG, "BT not enabled. Cannot set Remote Device pin");
            return false;
        }
        try {
            return sService.setPin(this, true, pin.length, pin);
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return false;
    
public booleansetRemoteOutOfBandData()

hide

        // TODO(BT)
        /*
        try {
          return sService.setRemoteOutOfBandData(this);
      } catch (RemoteException e) {Log.e(TAG, "", e);}*/
      return false;
    
public java.lang.StringtoString()
Returns a string representation of this BluetoothDevice.

Currently this is the Bluetooth hardware address, for example "00:11:22:AA:BB:CC". However, you should always use {@link #getAddress} if you explicitly require the Bluetooth hardware address in case the {@link #toString} representation changes in the future.

return
string representation of this BluetoothDevice

        return mAddress;
    
public voidwriteToParcel(android.os.Parcel out, int flags)


          
        out.writeString(mAddress);