Android SDK: Getting started
This guide explains how to install the Cartrack BLE Lock SDK for Android and run the basic connection flow against a compatible BLE terminal.
Installation
- Add the latest CartrackBleLock_Android_SDK
.aarfile to your Android project (for example, under alibs/directory). - In your project-level
build.gradle, addflatDir { dirs 'libs' }.
allprojects {
repositories {
...
flatDir {
dirs 'libs'
}
}
}
- In your app-level `build.gradle`, add the `.aar` file dependency.
```kotlin
dependencies {
implementation fileTree(include: ['*.aar'], dir: 'libs')
implementation(name: 'blesdk-release_v3.0.3.aar', ext: 'aar')
}
- For Android 12 (API 31) or higher, you must declare Bluetooth permissions.
- Update your app-level
AndroidManifest.xml.
<manifest>
<uses-permission android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...
</manifest>
Core Classes
BleService
The main entry point for the Cartrack BLE SDK. Use this class to initialize the SDK and obtain terminal instances.
Key Methods:
- BleService.configure() - Configures the BleService. This function should be called first.
- BleService.getTerminal() - Get an instance of BleTerminal associated with the given terminal ID.
- BleService.isConfigured() - Checks if the given BleTerminal instance is configured.
- BleService.clear() - Clears the configured instance.
BleTerminal
Represents a terminal that communicates with CTG devices via Bluetooth Low Energy.
Key Methods:
- BleTerminal.scanAndConnectToPeripheral - Connects to a BleTerminal device.
- BleTerminal.sendAction - Executes a Bluetooth Low Energy (BLE) action on the connected peripheral.
- BleTerminal.saveAuthKey - Encrypts the authentication key and saves it to Shared Preferences.
- BleTerminal.disconnect - Disconnects the peripheral from the BleTerminal.
- BleTerminal.getAuthKey - Retrieves the encrypted authentication key from Shared Preferences, decrypts it, and returns it.
- BleTerminal.getBleConnectionState - Retrieves the Bluetooth Low Energy (BLE) connection state of the device.
- BleTerminal.getLockState - Gets the current lock state of the vehicle.
- BleTerminal.hasKey - Checks if a terminal authentication key is available for secure communication.
- BleTerminal.removeAuthKey - Removes the authentication key from Shared Preferences.
BleListener
Interface for handling BLE events and callbacks.
Key Callbacks:
- BleListener.onError() - Called when an error occurs during a BleTerminal operation.
- BleListener.onReconnect() - Called when the Bluetooth GATT layer returns
GATT_ERRORorGATT_FAILURE. After three reconnect attempts, the SDK returnsBleError.GATTError. - BleListener.onRemoveAuthKeySuccess() - Called when the authentication key is successfully removed.
- BleListener.onSaveAuthKeySuccess() - Called when the authentication key is successfully saved.
- BleListener.onSignalStrength() - Called when the signal strength changes.
- BleListener.onTerminalCommandResult() - Called when a terminal command returns a result.
- BleListener.onTerminalConnected() - Called when the BleTerminal successfully connects to a device.
- BleListener.onTerminalDidGetVehicleStats() - Called when fetching vehicle stat.
- BleListener.onTerminalDidGetVehicleStatus() - Called when fetching vehicle status.
- BleListener.onTerminalDisconnected() - Called when terminal is disconnected.
How to Use
All examples require
import CartrackBleLockSDKsomewhere in the source file.
Initialize CartrackBleLockSDK
Initialize CartrackBleLockSDK with Context:
V2.4
BleService.configure(Context, vendorId, apiKey, countryCode)
V3.0
BleService.configure(Context)
Before starting to get the authentication key, you can create a BleTerminal variable outside the function:
var bleTerminal: BleTerminal
Get an instance of BleTerminal:
bleTerminal = BleService.getTerminal(terminalID)
Save Authentication Key
Save the authentication key with BleTerminal.saveAuthKey():
bleTerminal.saveAuthKey()
Get Authentication Key
Get the authentication key with BleTerminal.getAuthKey():
bleTerminal.getAuthKey()
This action requires network connection thus performing it earlier is encouraged before connecting to terminal.
Connect to Ble Terminal
Connect to Ble Terminal with BleTerminal.scanAndConnectToPeripheral():
V2.4
bleTerminal.scanAndConnectToPeripheral()
Under the hood, this scans peripherals around, connects and authenticates If successful, then you will get a response through BleListener.onTerminalConnected Else BleListener.onError if anything wrong happens:
- ErrorHandler.BleConnectionError.KeyNotFound
- ErrorHandler.BleConnectionError.KeyInvalid
- ErrorHandler.BleConnectionError.BluetoothUnsupported
- ErrorHandler.BleConnectionError.BluetoothUnauthorized > only if your app did not request the required permission
- ErrorHandler.BleConnectionError.LocationUnauthorized > only if your app did not request the required permission
- ErrorHandler.BleConnectionError.BluetoothPairingFailed > the system returned a connection error
- ErrorHandler.BleConnectionError.TerminalNotFound > 30 seconds timeout
V3.0
bleTerminal.scanAndConnectToPeripheral()
Under the hood, this scans peripherals around, connects and authenticates If successful, then you will get a response through BleListener.onTerminalConnected Else BleListener.onError if anything wrong happens:
- BleError.KeyNotFound
- BleError.KeyInvalid
- BleError.BluetoothUnsupported
- BleError.BluetoothUnauthorized > only if your app did not request the required permission
- BleError.LocationUnauthorized > only if your app did not request the required permission
- BleError.TerminalNotFound > the system returned a connection error
- BleError.TerminalNotFound > 30 seconds timeout
- BleError.GATTError > BluetoothGattCallback.onConnectionStateChange return other than GATT_SUCCESS
Connect to Ble Terminal with Timeout
Set connection timeout by add duration (second) in Long. Default timeout is 10 seconds:
bleTerminal.scanAndConnectToPeripheral(20)
Disconnect from Ble Terminal
Disconnect from Ble Terminal with BleTerminal.disconnect():
bleTerminal.disconnect()
This function will send a disconnect command to the terminal.
Fetch Authentication Key
Fetch authentication key from API BleTerminal.fetchAuthKey() from shared preferences:
bleTerminal.fetchAuthKey()
Remove Authentication Key
Remove the authentication key with BleTerminal.removeAuthKey() from shared preferences:
bleTerminal.removeAuthKey()
This function will not affect the authentication key on the server side.
Terminal Signal Update
Called periodically to update the BLE signal strength to Ble Terminal:
bleListener.onSignalStrength(BleSignalStrength, rssiValue)
Check Authentication Key
Called to checks if a terminal authentication key is available for secure communication:
bleListener.hasKey()
Send Ble Action to Terminal
Send lock action to terminal BleAction.LOCK:
bleTerminal.sendAction(BleAction.LOCK)
Send unlock action to terminal with BleAction.UNLOCK:
bleTerminal.sendAction(BleAction.UNLOCK)
Send headlight action to terminal with BleAction.HEADLIGHT:
bleTerminal?.sendAction(BleAction.HEADLIGHT)
Send horn action to terminal with BleAction.HORN:
bleTerminal.sendAction(BleAction.HORN)
Get the current state of vehicle's lock status - possible value - locked/unlocked with BleAction.GET_LOCK_STATE:
bleTerminal.sendAction(BleAction.GET_LOCK_STATE)
Send unlock with no key fob action to terminal with BleAction.UNLOCK_NOKEYFOB:
bleTerminal.sendAction(BleAction.UNLOCK_NOKEYFOB)
Get the current state of vehicle's status with BleAction.VEHICLE_GET_CONFIG:
bleTerminal.sendAction(BleAction.VEHICLE_GET_CONFIG)
Consist of
odometer,engineHours,engineRPM,fuelLevel,hazardsIsOn,indicators,brakesIsActive,handBrakeIsActive,lightsIsOn,driverDoorIsOpen,passengerDoorIsOpen,driverSeatbeltIsEngage,passengerSeatbeltIsEngage,hornIsActivefield.
Get the current state of vehicle's ignition status - possible value - on/off with BleAction.VEHICLE_GET_STATUS:
bleTerminal.sendAction(BleAction.VEHICLE_GET_STATUS)
V2.4
The response for all BleAction will be in BleListener.onTerminalCommandResult(bleAction: BleAction) and BleListener.onError(ErrorHandler.BleActionError/ErrorHandler.CtgError)
V3.0
The response for all BleAction will be in BleListener.onTerminalCommandResult(bleAction: BleAction) and BleListener.onError(BleError/BleError.CtgError)
Possible error in Ble
BleError
Error Handler related to BLE Connection.
- BluetoothUnauthorized - Bluetooth permission is not granted. Ask user to grant permission from phone settings
- BluetoothDisabled - Bluetooth is disabled
- BluetoothUnsupported - Device does not support Bluetooth Low Energy
- SaveAuthKeyFailed - Failed to save authentication key in Shared Preference
- KeyNotFound - Authentication key not found in Shared Preference
- KeyInvalid - Authentication key in Shared Preference is invalid
- TerminalNotFound - Unable to discover Ble Terminal, terminal might be out of range
- NotConnected - Not connected to Ble Terminal. Call BleTerminal.connect() to connect first
- LocationUnauthorized - Location permission is not granted
- GattError - Gatt Error. Called when BluetoothGatt onConnectionStateChange return other than GATT_SUCCESS.
- CtgError - Failed due to Terminal action, refer to CtgError
CtgError
Error Handler related to CTG Terminal.
- InvalidKey - Terminal response failed with invalid key
- Timeout - Terminal response failed with time out
- Fail - Terminal response failed, default return value
- NoKey - Terminal response failed with no key
- Unsuccessful - Terminal response failed with unsuccessful
- ScriptFail - Terminal response failed with script fail
- NoScript - Terminal response failed with no script
- TooManyRequest - Terminal response failed with exceed maximum 3 concurrent commands. Any additional commands can be sent once one of the 3 previously sent commands is completed
GattError
Gatt Error. Called when BluetoothGatt onConnectionStateChange return other than GATT_SUCCESS.
- GattReadNotPermitted: GATT read operation is not permitted
- GattWriteNotPermitted: GATT write operation is not permitted
- GattInsufficientAuthentication: Insufficient authentication for a given operation
- GattRequestNotSupported: The given request is not supported
- GattInvalidOffset: A read or write operation was requested with an invalid offset
- BleHciConnectionTimeout: Could not establish a connection in specified period. Maybe when distance for connect is so long or device is currently connected to something else.
- BleHciStatusCodeCommandDisallowed: The BLE device doesn't allow the command you're trying to send
- GattInvalidAttributeLength: The data you're trying to send or receive is the wrong length
- GattInsufficientEncryption: The connection to the BLE device isn't secure enough
- BleHciStatusCodeInvalidBtleCommandParameters: The parameters you're using for the BLE command are invalid
- BleHciRemoteUserTerminatedConnection: The user on the other end terminated the BLE connection
- BleHciRemoteDevTerminationDueToLowResources: The BLE device terminated the connection because it's low on resources
- BleHciRemoteDevTerminationDueToPowerOff: The BLE device terminated the connection because it's powering off
- BleHciLocalHostTerminatedConnection: Your device terminated the BLE connection
- BleHciUnsupportedRemoteFeature: The BLE device doesn't support a feature that your device needs
- BleHciStatusCodeInvalidLmpParameters: The parameters for the Link Manager Protocol (LMP) are invalid
- BleHciStatusCodeUnspecifiedError: An unspecified error occurred with the BLE connection
- BleHciStatusCodeLmpResponseTimeout: The LMP response timed out
- BleHciStatusCodeLmpPduNotAllowed: The LMP Protocol Data Unit (PDU) isn't allowed
- BleHciInstantPassed: The instant you specified has already passed
- BleHciPairingWithUnitKeyUnsupported: The BLE device doesn't support pairing with a unit key
- BleHciDifferentTransactionCollision: A different BLE transaction collided with the current one
- BleHciControllerBusy: The BLE controller is busy and can't handle your request
- BleHciConnIntervalUnacceptable: The connection interval you requested is unacceptable to the BLE device
- BleHciDirectedAdvertiserTimeout: The directed advertising procedure timed out before a connection could be established
- BleHciConnTerminatedDueToMicFailure: The BLE connection was terminated due to a microphone failure. This could indicate a hardware issue with the microphone or a problem with the audio processing on the device.
- BleHciConnFailedToBeEstablished: The BLE connection failed to be established. This could be due to a variety of reasons, such as the device being out of range, the device being turned off, or a problem with the BLE stack on either device
- GATTNoRessources: The BLE device does not have enough resources to complete the request. This could be due to the device being low on memory or processing power
- GATTInternalError: An internal error occurred on the BLE device. This is a generic error that could indicate a variety of problems
- GATTWrongState: The BLE device is in the wrong state to complete the request. This could be due to the device not being connected or not being in the correct mode
- GATTDbFull: The BLE device's database is full. This could prevent the device from storing new data or updating existing data
- GATTBusy: The BLE device is busy and cannot handle the request at this time. This could be due to the device processing other requests or performing other tasks
- GATTError: A generic GATT error occurred. This is a catch-all error that could indicate a variety of problems
- GattIllegalParameter: An illegal parameter was passed to the GATT function. This could be due to an incorrect value being passed or a parameter being missing
- GattAuthFail: Authentication failed when attempting to connect to the BLE device. This could be due to an incorrect password or pairing key
- GattConnectionCongested: The BLE connection is congested. This could be due to too many devices being connected to the device or too much data being transferred
- GattConnectionTimeout: The BLE connection timed out. This could be due to the device being out of range or the device being turned off
- GattFailure: A generic GATT failure occurred
- Error: GATT error did not recover
API Reference
For complete API documentation with detailed method signatures, parameters, and examples, see:
- BleService - SDK initialization and configuration
- BleTerminal - Terminal operations and vehicle control
- BleListener - Event handling and callbacks
Next Steps
- Set up your development environment by following the installation steps above.
- Implement error handling using the error types documented above.
- Test with a physical device to ensure reliable BLE connectivity.