# Modules.Bluetooth

Allows a Titanium application to use Bluetooth service.

Availability
1.0.0

# Overview

The module is used for connecting your application via bluetooth.

You can download the module at appcelerator.bluetooth (opens new window)

# Getting Started

  • Add the module as a dependency to your application by adding a <module> item to the <modules> element of your tiapp.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

Availability
1.0.0
address :String

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.


# apiName READONLY

Availability
3.2.0
apiName :String

The name of the API that this proxy corresponds to.

The value of this property is the fully qualified name of the API. For example, Titanium.UI.Button returns Ti.UI.Button.


# bubbleParent

Availability
3.0.0
bubbleParent :Boolean

Indicates if the proxy will bubble an event to its parent.

Some proxies (most commonly views) have a relationship to other proxies, often established by the add() method. For example, for a button added to a window, a click event on the button would bubble up to the window. Other common parents are table sections to their rows, table views to their sections, and scrollable views to their views. Set this property to false to disable the bubbling to the proxy's parent.

Default: true


# lifecycleContainer

Availability
3.6.0

The Window or TabGroup whose Activity lifecycle should be triggered on the proxy.

If this property is set to a Window or TabGroup, then the corresponding Activity lifecycle event callbacks will also be called on the proxy. Proxies that require the activity lifecycle will need this property set to the appropriate containing Window or TabGroup.


# name

Availability
1.0.0
name :String

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

Availability
1.0.0
scanMode :Number

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

Availability
1.0.0
state :Number

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

# addEventListener

Availability
1.0.0
addEventListener(name, callback) void

Adds the specified callback as an event listener for the named event.

Parameters

Name Type Description
name String

Name of the event.

callback Callback<Titanium.Event>

Callback function to invoke when the event is fired.

Returns

Type
void

# applyProperties

Availability
3.0.0
applyProperties(props) void

Applies the properties to the proxy.

Properties are supplied as a dictionary. Each key-value pair in the object is applied to the proxy such that myproxy[key] = value.

Parameters

Name Type Description
props Dictionary

A dictionary of properties to apply.

Returns

Type
void

# cancelDiscovery

Availability
1.0.0
cancelDiscovery() Boolean

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

Availability
1.0.0
checkBluetoothAddress(address) Boolean

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

Availability
1.0.0
createServerSocket(params) Modules.Bluetooth.BluetoothServerSocket

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

Availability
1.0.0
disable() Boolean

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

Availability
1.0.0
enable() Boolean

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

Availability
1.0.0
ensureDiscoverable([interval]) void

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

# fireEvent

Availability
1.0.0
fireEvent(name[, event]) void

Fires a synthesized event to any registered listeners.

Parameters

Name Type Description
name String

Name of the event.

event Dictionary

A dictionary of keys and values to add to the Titanium.Event object sent to the listeners.

Returns

Type
void

# getName

Availability
1.0.0
getName() String

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

Availability
1.0.0
getPairedDevices() PairedDevicesType

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


# getRemoteDevice

Availability
1.0.0
getRemoteDevice(address) Modules.Bluetooth.BluetoothDevice

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

Availability
1.0.0
isDiscovering() Boolean

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

Availability
1.0.0
isEnabled() Boolean

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

Availability
1.0.0
isRequiredPermissionsGranted() Boolean

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

Availability
1.0.0
isSupported() Boolean

Determines whether Bluetooth is supported on the local Bluetooth device.

Returns

Returns true if Bluetooth is supported on the device, false otherwise.

Type
Boolean

# removeEventListener

Availability
1.0.0
removeEventListener(name, callback) void

Removes the specified callback as an event listener for the named event.

Multiple listeners can be registered for the same event, so the callback parameter is used to determine which listener to remove.

When adding a listener, you must save a reference to the callback function in order to remove the listener later:

var listener = function() { Ti.API.info("Event listener called."); }
window.addEventListener('click', listener);

To remove the listener, pass in a reference to the callback function:

window.removeEventListener('click', listener);

Parameters

Name Type Description
name String

Name of the event.

callback Callback<Titanium.Event>

Callback function to remove. Must be the same function passed to addEventListener.

Returns

Type
void

# requestAccessFinePermission

Availability
1.0.0
requestAccessFinePermission([callback]) Promise<Titanium.Android.RequestPermissionAccessResult>

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

Availability
2.0.0
requestPermissions([callback]) Promise<Titanium.Android.RequestPermissionAccessResult>

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

Availability
1.0.0
setName(name) void

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

Availability
1.0.0
startDiscovery() Boolean

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

Availability
1.0.0

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.


# discoveryFinished

Availability
1.0.0

Fired when the local Bluetooth adapter finished discovery.


# discoveryStarted

Availability
1.0.0

Fired when the local Bluetooth adapter started discovery.


# stateChanged

Availability
1.0.0

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

Availability
1.0.0
DEVICE_TYPE_CLASSIC :Number

One of the possible values returned by the type property.


# DEVICE_TYPE_DUAL

Availability
1.0.0
DEVICE_TYPE_DUAL :Number

One of the possible values returned by the type property.


# DEVICE_TYPE_LE

Availability
1.0.0
DEVICE_TYPE_LE :Number

One of the possible values returned by the type property.


# DEVICE_TYPE_UNKNOWN

Availability
1.0.0
DEVICE_TYPE_UNKNOWN :Number

One of the possible values returned by the type property.


# SCAN_MODE_CONNECTABLE

Availability
1.0.0
SCAN_MODE_CONNECTABLE :Number

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

Availability
1.0.0
SCAN_MODE_CONNECTABLE_DISCOVERABLE :Number

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

Availability
1.0.0
SCAN_MODE_NONE :Number

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

Availability
1.0.0
STATE_OFF :Number

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

Availability
1.0.0
STATE_ON :Number

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

Availability
1.0.0
STATE_TURNING_OFF :Number

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

Availability
1.0.0
STATE_TURNING_ON :Number

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.