# Modules.Bluetooth
Allows a Titanium application to use Bluetooth service.
# Overview
The module is used for connecting your application via bluetooth.
Note: This feature requires a Pro or Enterprise subscription. More infos here!
# Getting Started
- Add the module as a dependency to your application by adding a
<module>
item to the<modules>
element of yourtiapp.xml
file:<ti:app> <!-- ... --> <modules> <module platform="android">appcelerator.bluetooth</module> </modules> <!-- ... --> </ti:app>
- Use
require()
to access the module from JavaScript:var bluetooth = require('appcelerator.bluetooth');
- The
bluetooth
variable is a reference to the module. Make API calls using this reference:bluetooth.isSupported();
# Example application
Please see the /modules/android/appcelerator.bluetooth/x.y.z (version of module)/example folder.
# Observations
- On a bluetooth socket object with a given
uuid
, if device A connects to device B and the same device A tries to create another socket object with the same uuid and attempts to connect with the same device B, then it won't be successful to connect because socket connection is already established between them. Moreover, while attempting for the new connect, the existing connection would also get disconnected.Recommendation:
It would always be recommended to close the socket connection properly before trying to connect using the newly created socket object on the same device and same uuid. - When device scanning/discovery is in-progress, the same device can be found multiple times from the deviceFound event in span of 12 seconds. This scenario should be handled by the application. More information refer to deviceFound event and startDiscovery method.
# Examples
# How to Check if Bluetooth is supported on your device.
if(bluetooth.isSupported())
{
Ti.API.info('Bluetooth is supported');
} else
{
Ti.API.info('Bluetooth is not supported in this device');
}
# How to get paired devices with local adapter.
var dict = bluetooth.getPairedDevices();
var device = []; // array for paired devices.
if (dict.success) {
var pdevices = dict.pairedDevices;
for (var index = 0; index < pdevices.length; index++){
device[index] = pdevices[index];
}
} else {
//Failed to get paired devices.
Ti.API.info(dict.message);
}
# To creates an object of the BluetoothServerSocketProxy class.
This object can be used to listen the incoming connections.
var serverSocket = bluetooth.createServerSocket({
name: 'Test_Server_Socket',
uuid: '8ce255c0-200a-11e0-ac64-0800200c9a66',
secure: true
});
// To accept the incoming connections.
serverSocket.startAccept(false);
# If you want to get bluetooth device information
To get the bluetooth device name.
var btName = bluetooth.name;
And to check the current state
var state = bluetooth.state;
if(state === bluetooth.STATE_ON)
{
Ti.API.info('Bluetooth is on');
}
# Properties
# address READONLY
The hardware address of the local Bluetooth adapter.
For example "00:11:22:AA:BB:CC". This method will only return valid address if the android API < 23.
Otherwise, it will return a constant value of 02:00:00:00:00:00
.
# name
Friendly name of the local Bluetooth adapter.
This name is visible to remote Bluetooth devices. In case of error it can be null.
# scanMode READONLY
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_CONNECTABLE, SCAN_MODE_CONNECTABLE_DISCOVERABLE and SCAN_MODE_NONE. If Bluetooth state is not STATE_ON, this API will return SCAN_MODE_NONE. After turning the Bluetooth on, wait for the stateChanged event with STATE_ON to get the updated value. If Bluetooth is not supported on the device, this property returns an error number which is different from the possible values.
# state READONLY
The current state of the local Bluetooth adapter.
Possible values are STATE_OFF, STATE_ON, STATE_TURNING_OFF, STATE_TURNING_ON If Bluetooth is not supported on the device, this property returns an error number which is different from the possible values.
# Methods
# cancelDiscovery
Cancels the current device discovery process.
As discovery is a heavyweight procedure for the Bluetooth adapter, this method should always be called before attempting to connect to a remote device via connect. Discovery 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 or if there is no ongoing discovery process this function will return false. Listen for the discoveryFinished event to be notified when the device discovery process finished.
Returns
true on success, false on error
- Type
- Boolean
# checkBluetoothAddress
Validates a Bluetooth address, such as "00:43:A8:23:10:F0". Alphabetic characters must be uppercase to be valid.
Parameters
Name | Type | Description |
---|---|---|
address | String | a string representing the address, such as "00:43:A8:23:10:F0". |
Returns
Returns true if the address is valid, false otherwise.
- Type
- Boolean
# createServerSocket
Creates an object of Modules.Bluetooth.BluetoothServerSocket which can be used to listen for incoming connections.
This method, when called, creates an object of Modules.Bluetooth.BluetoothServerSocket which can be used to listen for the incoming connection and accept it by calling the startAccept method. This method returns null, if Bluetooth is not supported on the device.
Parameters
Name | Type | Description |
---|---|---|
params | ServerSocketType | Dictionary which contains value for name, uuid and security level. |
Returns
listening socket for the device
# disable
Disables the local Bluetooth adapter.
Listen for the stateChanged event to be notified when the local Bluetooth adapter is turning off.
Returns
Returns true if the process is initiated successfully or when the bluetooth is already off.
- Type
- Boolean
# enable
Enables the local Bluetooth adapter.
Listen for the stateChanged event to be notified when the local Bluetooth adapter is turning on.
Returns
Returns true if the process is initiated successfully or when the bluetooth is already on.
- Type
- Boolean
# ensureDiscoverable
Make the local device discoverable to other devices.
Displays a system activity that asks the user for permission to make the local device discoverable by other devices, and to turn on Bluetooth if it is not currently enabled. Change the scan mode to SCAN_MODE_CONNECTABLE_DISCOVERABLE. By default, the device becomes discoverable for 300 seconds, or 5 minutes. You can define a different duration, up to 3600 seconds or 1 hour.
Parameters
Name | Type | Description |
---|---|---|
interval | Number | It represents the time duration in seconds to make local device discoverable. |
Returns
- Type
- void
# getName
Gets the friendly Bluetooth name of the local Bluetooth adapter.
Returns
Name of the local Bluetooth adapter. In case of error it can be null.
- Type
- String
# getPairedDevices
This method is use to get the devices that are paired to the local Bluetooth adapter.
Returns the PairedDevicesType. In this if the paired devices are successfully fetched then the success will be true and can get array of paired devices with the pairedDevices. If it is false then we can get description of it via message If there's any issue fetching paired device, or if there no paired devices then this methods return false. Refer message for detailed reason of failure.
Returns
Dictionary of arguments passed by the method, e.g. success, message and pairedDevices
- Type
- PairedDevicesType
# getRemoteDevice
Get a Modules.Bluetooth.BluetoothDevice object for the given Bluetooth hardware address.
If Bluetooth is not supported on the device, this method return null.
Parameters
Name | Type | Description |
---|---|---|
address | String | Valid Bluetooth hardware addresses must be upper case, in a format such as "00:11:22:33:AA:BB".. |
Returns
Object of the Modules.Bluetooth.BluetoothDevice
# isDiscovering
Determines whether the local Bluetooth adapter is currently in the device discovery process or not.
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. If Bluetooth is not supported on the device or Bluetooth state is not STATE_ON this function will return false.
Returns
true if the local Bluetooth adapter is currently in the device discovery process.
- Type
- Boolean
# isEnabled
Determines if Bluetooth is currently enabled and ready for use.
If Bluetooth is not supported on the device, this method will return false.
Returns
Returns true if the local adapter is on.
- Type
- Boolean
# isRequiredPermissionsGranted
Determines whether the required permissions are granted or not.
Checks if the following permissions are defined and have been granted by the user:
android.permission.ACCESS_FINE_LOCATION
android.permission.BLUETOOTH
android.permission.BLUETOOTH_ADMIN
android.permission.BLUETOOTH_ADVERTISE
android.permission.BLUETOOTH_CONNECT
android.permission.BLUETOOTH_SCAN
If this method returns false
, then you should call the
requestPermissions method to display a dialog
requesting permissions from the user.
Returns
Returns true if all the permissions are granted.
- Type
- Boolean
# isSupported
Determines whether Bluetooth is supported on the local Bluetooth device.
Returns
Returns true if Bluetooth is supported on the device, false otherwise.
- Type
- Boolean
# requestAccessFinePermission
Displays a dialog requesting location permission from the user.
Displays a dialog requesting the user for the ACCESS_FINE_LOCATION
permission.
This permission is required by the startDiscovery method.
The dialog will not be dispayed if permission has already been granted.
The given optional callback argument and returned Promise
will provide a success
property
indicating if permission was granted or not.
Parameters
Name | Type | Description |
---|---|---|
callback | Callback<Titanium.Android.RequestPermissionAccessResult> | Function to be invoked indicating if permission was granted or not. |
Returns
As of 2.0.0, this method will return a Promise
whose resolved value is equivalent to that passed to the optional callback argument.
- Type
- Promise<Titanium.Android.RequestPermissionAccessResult>
# requestPermissions
Displays a dialog requesting all permissions needed by the bluetooth module from the user.
Displays a dialog requesting the user for the ACCESS_FINE_LOCATION
permission.
Will also request the BLUETOOTH_ADVERTISE
, BLUETOOTH_CONNECT
, and BLUETOOTH_SCAN
permissions
if running on Android 12 or higher. These permission are required by this module to
discover devices and to make the app's device discoverable by other devices.
The given optional callback argument and returned Promise
will provide a success
property
indicating if permissions were granted or not.
Parameters
Name | Type | Description |
---|---|---|
callback | Callback<Titanium.Android.RequestPermissionAccessResult> | Function to be invoked indicating if permissions were granted or not. |
Returns
Returns a Promise
whose resolved value is equivalent to that passed to the optional callback argument.
- Type
- Promise<Titanium.Android.RequestPermissionAccessResult>
# setName
Sets the friendly Bluetooth name of the local Bluetooth adapter.
The Bluetooth adapter must be turned on before you can set the name. After turning the Bluetooth on, wait for the stateChanged event with STATE_ON to get the updated value.
Parameters
Name | Type | Description |
---|---|---|
name | String | Name for the local Bluetooth adapter. Bluetooth names can be maximum of 248 bytes using UTF-8 encoding. Although, it may vary upon Bluetooth devices. Some can only display first 40 characters, and some may be limited to just 20. |
Returns
- Type
- void
# startDiscovery
Starts the remote device discovery process.
This method starts the discovery for the nearby Bluetooth devices. The process of the discovery
takes upto 12 seconds.This is an asynchronous call, it will return immediately. Register for
discoveryStarted and discoveryFinished
events to determine exactly when discovery starts and completes. Register for deviceFound
event to be notified when a nearby device is found. From API level 29 and above make sure
that the location services is on in the device to start the scanning process. Device discovery
will only find remote devices that are currently in discoverable mode. Many Bluetooth devices
are not discoverable by default, and need to be entered into a discoverable mode. This method may
return same device multiple times from the deviceFound
event in span of 12 seconds.
If Bluetooth state is not STATE_ON or the required permission
not granted than this function will return false.
Returns
Returns true to indicate success, or false on immediate error.
- Type
- Boolean
# Events
# deviceFound
Fired when the local Bluetooth adapter discovers a device.
This event may get called several times for the same Bluetooth device in the range. For not listing the same Bluetooth device many times, one should add a check before adding it to the list. You can do following to avoid the above.
// Extract the device from this event properties.
var device = e.device;
var numRows = btDevicesListSection.rowCount; // count the number of rows in the section where rows are added.
if(numRows > 0)
{
var rowArray = btDevicesListSection.rows; // Extract all the rows into an array.
for(var i =0; i< numRows; i++)
{
//Check if the already added row with the id is same as newly found device.
// The id is the property of the row. You should add device address into it.
if(rowarray[i].id == device.address)
{
//update the device info. Some devices might get updated and changed the friendly name.
return;
}
}
}
Properties
Name | Type | Description |
---|---|---|
device | Modules.Bluetooth.BluetoothDevice | The discovered Bluetooth device. |
RSSI | Number | The RSSI value at the time of device discovery. |
source | Object | Source object that fired the event. |
type | String | Name of the event fired. |
bubbles | Boolean | True if the event will try to bubble up if possible. |
cancelBubble | Boolean | Set to true to stop the event from bubbling. |
# stateChanged
Fired when the state of the local Bluetooth adapter changes.
Most possible reason for this event to occur is either bluetooth is turning on or off.
# Constants
# DEVICE_TYPE_CLASSIC
One of the possible values returned by the type property.
# DEVICE_TYPE_DUAL
One of the possible values returned by the type property.
# DEVICE_TYPE_UNKNOWN
One of the possible values returned by the type property.
# SCAN_MODE_CONNECTABLE
One of the possible values returned by the scanMode property.
This value 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 Bluetooth devices that have previously discovered this devices.
# SCAN_MODE_CONNECTABLE_DISCOVERABLE
One of the possible values returned by the scanMode property.
This value 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.
# SCAN_MODE_NONE
One of the possible values returned by the scanMode property.
This value indicated that both inquiry and page scan is disabled on the local Bluetooth adapter. Therefore this device neither discoverable nor connectable from the remote Bluetooth devices.
# STATE_OFF
One of the possible values returned by the state property. This value indicates that the local Bluetooth adapter is off.
Listen for the stateChanged event to be notified when the local Bluetooth adapter is off.
# STATE_ON
One of the possible values returned by the state property. This value indicates that the local Bluetooth adapter is on, and ready for use.
Listen for the stateChanged event to be notified when the local Bluetooth adapter is on.
# STATE_TURNING_OFF
One of the possible values returned by the state property. This value indicates that the local Bluetooth adapter is turning off.
Listen for the stateChanged event to be notified when the local Bluetooth adapter is turning off.
# STATE_TURNING_ON
One of the possible values returned by the state property. This value indicates that the local Bluetooth adapter is turning on.
Listen for the stateChanged event to be notified when the local Bluetooth adapter is turning on.