appcelerator.bluetooth
A collection of API's to connect and communicate with device via Bluetooth
Install
A module is a zip you unpack in your project. There is no installer command yet - a ti module install is planned but does not exist today, so the steps below are the ones that work.
1. Download the release archive
2. Unpack it at your project root
cd /path/to/your-project unzip ~/Downloads/appcelerator.bluetooth-android-3.0.0.zipThe archive already contains the full path, so it lands in place:
- modules/android/appcelerator.bluetooth/3.0.0/
3. Add it to
tiapp.xml<modules> <module platform="android" version="3.0.0">appcelerator.bluetooth</module> </modules>The
platformattribute is the packager’s name for the platform, which isiphonefor iOS - the same word the archive uses in its own path.4. Require it from your app
const mod = require('appcelerator.bluetooth');
Manifest
Android 3.0.0
- Minimum SDK
- 12.7.0.GA
- Module API version
- 4
- Architectures
- arm64-v8a, armeabi-v7a, x86, x86_64
- GUID
- d4c8bc3c-dce5-48b4-9c7e-5ccb5102f205
- Author
- Axway
- License
- Proprietary
- Copyright
- Copyright (c) 2020 by Axway, Inc.
API reference
Compiled from tidev/appcelerator.bluetooth@3.0.0 (8ecbe7b).
Modules.Bluetooth
Extends Titanium.Module
Allows a Titanium application to use Bluetooth service.
The module is used for connecting your application via bluetooth.
You can download the module at appcelerator.bluetooth
Getting Started
- Add the module as a dependency to your application by adding a
<module>item to the[modules](api:Modules)element of yourtiapp.xmlfile:<ti:app> <!-- ... --> [modules](api:Modules) <module platform="android">appcelerator.bluetooth</module> </modules> <!-- ... --> </ti:app> - Use
require()to access the module from JavaScript:var bluetooth = require('appcelerator.bluetooth'); - The
bluetoothvariable 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 15
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.
One of the possible values returned by the type property.
One of the possible values returned by the type property.
One of the possible values returned by the type property.
One of the possible values returned by the type property.
Friendly name of the local Bluetooth adapter.
This name is visible to remote Bluetooth devices. In case of error it can be null.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Methods 17
cancelDiscovery
since 1.0.0Cancels 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.
true on success, false on error
checkBluetoothAddress
since 1.0.0Validates a Bluetooth address, such as "00:43:A8:23:10:F0". Alphabetic characters must be uppercase to be valid.
| Parameters | Type | Description |
|---|---|---|
| address | String | a string representing the address, such as "00:43:A8:23:10:F0". |
Returns true if the address is valid, false otherwise.
createServerSocket
since 1.0.0Creates an object of BluetoothServerSocket which can be used to listen for incoming connections.
This method, when called, creates an object of 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 | Type | Description |
|---|---|---|
| params | ServerSocketType | Dictionary which contains value for name, uuid and security level. 3 fields
|
disable
since 1.0.0Disables the local Bluetooth adapter.
Listen for the stateChanged event to be notified when the local Bluetooth adapter is turning off.
Returns true if the process is initiated successfully or when the bluetooth is already off.
enable
since 1.0.0Enables the local Bluetooth adapter.
Listen for the stateChanged event to be notified when the local Bluetooth adapter is turning on.
Returns true if the process is initiated successfully or when the bluetooth is already on.
ensureDiscoverable
since 1.0.0Make 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 | Type | Description |
|---|---|---|
| interval? | Number | It represents the time duration in seconds to make local device discoverable. |
getName
since 1.0.0Gets the friendly Bluetooth name of the local Bluetooth adapter.
Name of the local Bluetooth adapter. In case of error it can be null.
getPairedDevices
since 1.0.0This 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.
Dictionary of arguments passed by the method, e.g. success, message and pairedDevices
getRemoteDevice
since 1.0.0Get a BluetoothDevice object for the given Bluetooth hardware address.
If Bluetooth is not supported on the device, this method return null.
| Parameters | Type | Description |
|---|---|---|
| address | String | Valid Bluetooth hardware addresses must be upper case, in a format such as "00:11:22:33:AA:BB".. |
isDiscovering
since 1.0.0Determines 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.
true if the local Bluetooth adapter is currently in the device discovery process.
isEnabled
since 1.0.0Determines if Bluetooth is currently enabled and ready for use.
If Bluetooth is not supported on the device, this method will return false.
Returns true if the local adapter is on.
isRequiredPermissionsGranted
since 1.0.0Determines 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_LOCATIONandroid.permission.BLUETOOTHandroid.permission.BLUETOOTH_ADMINandroid.permission.BLUETOOTH_ADVERTISEandroid.permission.BLUETOOTH_CONNECTandroid.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 true if all the permissions are granted.
isSupported
since 1.0.0Determines whether Bluetooth is supported on the local Bluetooth device.
Returns true if Bluetooth is supported on the device, false otherwise.
requestAccessFinePermission
since 1.0.0Displays 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 | Type | Description |
|---|---|---|
| callback? | Callback<Titanium.Android.RequestPermissionAccessResult> | Function to be invoked indicating if permission was granted or not. |
As of 2.0.0, this method will return a Promise whose resolved value is equivalent to that passed to the optional callback argument.
requestPermissions
since 2.0.0Displays 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 | Type | Description |
|---|---|---|
| callback? | Callback<Titanium.Android.RequestPermissionAccessResult> | Function to be invoked indicating if permissions were granted or not. |
Returns a Promise whose resolved value is equivalent to that passed to the optional callback argument.
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 | 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. |
startDiscovery
since 1.0.0Starts 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 true to indicate success, or false on immediate error.
Events 4
deviceFound
since 1.0.0Fired 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;
}
}
}
| Event properties | Type | Description |
|---|---|---|
| device | Modules.Bluetooth.BluetoothDevice | The discovered Bluetooth device. |
| RSSI | Number | The RSSI value at the time of device discovery. |
discoveryFinished
since 1.0.0Fired when the local Bluetooth adapter finished discovery.
discoveryStarted
since 1.0.0Fired when the local Bluetooth adapter started discovery.
stateChanged
since 1.0.0Fired 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.
Modules.Bluetooth.BluetoothDevice
Extends Titanium.Proxy
Represents a remote bluetooth device.
A BluetoothDevice object lets you create a connection with the remote device or query information
about it, such as the name, address, UUID and type.
Properties 4
Address of the remote Bluetooth device.
This property returns the Bluetooth hardware address as string. For example, "00:11:22:AA:BB:CC".
Name of the remote Bluetooth device.
This property returns the Bluetooth name or null if there was a problem.
Type of the remote Bluetooth device.
Possible values are DEVICE_TYPE_UNKNOWN, DEVICE_TYPE_CLASSIC, DEVICE_TYPE_DUAL and DEVICE_TYPE_LE.
The supported UUIDs of the remote device.
This property does not start a service discovery procedure to retrieve the UUIDs from the remote device. Rather, the local cached copy of the service UUIDs are returned. Can be null on error.
Methods 2
createSocket
since 1.0.0Creates an RFCOMM Bluetooth socket.
This method, when called, creates an RFCOMM Bluetooth socket ready to start an outgoing connection to the remote device using SDP lookup of UUID.
| Parameters | Type | Description |
|---|---|---|
| uuid | String | UUID of the service this socket will connect to. |
| secure? | Boolean | Determines whether the connection will be secure or insecure. |
fetchUUIDs
since 1.0.0Perform a service discovery on the remote device to get the UUIDs supported.
The outcome of the discovery is reported via the fetchedUUIDs event.
Returns true if service discovery started successfully.
Events 1
fetchedUUIDs
since 1.0.0Fired when the UUIDs of the remote device are received using SDP.
| Event properties | Type | Description |
|---|---|---|
| device | Modules.Bluetooth.BluetoothDevice | The Bluetooth device in question. |
| UUIDs | Array<String> | The service UUIDs of the device. |
Modules.Bluetooth.BluetoothServerSocket
Extends Titanium.Proxy
A listening Bluetooth socket.
The purpose of the BluetoothSocketServer object is to listen for incoming connection requests
and provide a connected BluetoothSocket after a request is accepted.
Methods 4
close
since 1.0.0Closes the server socket.
This method, when called, closes the server socket. One cannot start accepting connections again after calling this method. On error, this method will throw an exception.
isAccepting
since 1.0.0Determines whether the server socket is currently accepting connections.
True if the server socket is accepting connections, false otherwise.
startAccept
since 1.0.0Inform the server socket to start accepting incoming connections.
This method, when called, starts listening for the incoming Bluetooth connections and block until a connection is established. Listen for the connectionReceived event to be notified when a connection is received or the error event when an error occured during accepting connection.
| Parameters | Type | Description |
|---|---|---|
| keepListening? | Boolean | Defines whether the server socket should keep listening after an incoming connection was received. If this parameter is false, it will stop accepting connections after a single connection is recieved. |
stopAccept
since 1.0.0Inform the server socket to stop accepting incoming connections.
This method, when called stop accepting incoming connections. One can again start accepting connections via startAccept method after calling this method. On error, this method will throw an exception.
Events 2
connectionReceived
since 1.0.0Fired when the server socket receives an incoming connection.
| Event properties | Type | Description |
|---|---|---|
| socket | Modules.Bluetooth.BluetoothSocket | The socket object bind to the connection. |
error
since 1.0.0Fired when a socket operation fails.
| Event properties | Type | Description |
|---|---|---|
| errorMessage | String | Description of the error. |
Modules.Bluetooth.BluetoothSocket
Extends Titanium.Proxy
A connected or connecting Bluetooth socket.
The BluetoothSocket object used to make a connection to the remote device. It is used to both
initiate an outgoing connection and to manage the connection.
Properties 1
The size of the read buffer in bytes. By default, the buffer size is 4*1024 bytes.
Methods 9
cancelConnect
since 1.0.0Drops the ongoing connection attempt if in progress.
If there is no connection attempt in progress, it does nothing.
close
since 1.0.0Closes the socket.
Listen for the disconnected event to be notified when socket is closed or the error in case of failure.
connect
since 1.0.0Starts the connection to the remote device.
This call will block until a connection is established or the connection fails. Listen for the connected event to be notified when the connection is established.
getReadBufferSize
since 1.0.0Get the size of the read buffer in bytes.
Size of the read buffer in bytes.
getRemoteDevice
since 1.0.0Get the remote device this socket is associated with.
The object representing the device to which this socket is connected to.
isConnected
since 1.0.0Determines whether there is an active connection with the remote device.
connection status of this socket
isConnecting
since 1.0.0Determines whether there is an ongoing connection attempt in progress.
True if connection attempt in progress false otherwise
setReadBufferSize
since 1.0.0Sets the size of the read buffer in bytes.
You can set the read buffer size at any time, but it will only take effect during the next connection. By default, the buffer size is 4*1024 bytes.
| Parameters | Type | Description |
|---|---|---|
| newReadBufferSize | Number | The desired size of the read buffer in bytes. |
write
since 1.0.0Sends an array of bytes over the socket.
If the socket is not connected, then this method will throw an error.
| Parameters | Type | Description |
|---|---|---|
| buffer | Titanium.Buffer | Represents the data to be sent over the socket. |
Events 4
connected
since 1.0.0Fired when the connection through the socket is established.
| Event properties | Type | Description |
|---|---|---|
| socket | Modules.Bluetooth.BluetoothSocket | The socket through which the connection was made. |
disconnected
since 1.0.0Fired when connection to the socket is lost.
| Event properties | Type | Description |
|---|---|---|
| socket | Modules.Bluetooth.BluetoothSocket | The socket on which the data was received. |
| message | String | The localized message of the exception that accompanies the disconnect event. The localized message is |
error
since 1.0.0Fired when an operation fails.
| Event properties | Type | Description |
|---|---|---|
| socket | Modules.Bluetooth.BluetoothSocket | The socket that encounter the error. |
| errorMessage | String | The error message for the error encountered on the socket. The error can be encountered while performing any socket operations like- socket connecting to remote device, cancelling the connecting operation, closing the socket, socket connection gets lost etc. Note:- If the error message "Device connection was lost." comes, that signifies the connection with the socket is lost which can occur if the device goes out of bluetooth range, remote device deliberately disconnects the connection, etc. |
receivedData
since 1.0.0Fired when data is received on this socket.
| Event properties | Type | Description |
|---|---|---|
| socket | Modules.Bluetooth.BluetoothSocket | The socket on which the data was received. |
| data | Titanium.Buffer | A buffer object holding the data received. |