If the desired connection is BLE (Bluetooth Low Energy), a minimum SDK level of 18 is required. All communication is handled by the BluetoothLEController.
import android.bluetooth.BluetoothAdapter;
Define a BluetoothAdapter for the project
private BluetoothAdapter mBtAdapter = null;
Define the routine that will start scanning for BLE devices, and stop after a timeout value is reached. You need to pass a callback to the BluetoothAdapter that will execute when a BLE device is found.
private void scanLeDevice(final boolean enable, long timeout) {
if (enable) {
handler.postDelayed(new Runnable() {
public void run() {
mBtAdapter.stopLeScan(mLeScanCallback);
}
}, timeout);
mBtAdapter.startLeScan(mLeScanCallback);
} else {
mBtAdapter.stopLeScan(mLeScanCallback);
}
}
Define the callback. When a device is found, a match can be determined by the device name or the device MAC address. If found, execute setBluetoothDevice on that device.
private String BLE_Id = "BLE_NAME";
private boolean btleDeviceRegistered = false;
private String btleDeviceAddress = "";
private final long BLE_ScanTimeout = 5000;
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice btledevice, int rssi,
byte[] scanRecord) {
if (BLE_Id != null)
{
if (BLE_Id.length() == 17 && BLE_Id.charAt(2) == ':' && BLE_Id.charAt(5) == ':' && BLE_Id.charAt(8) == ':' &&
BLE_Id.charAt(11) == ':' && BLE_Id.charAt(14) == ':')
{
String deviceAddress = btledevice.getAddress();
if (deviceAddress != null && deviceAddress.equalsIgnoreCase(BLE_Id))
{
BluetoothLEController.setBluetoothDevice(btledevice);
btleDeviceAddress = deviceAddress;
if (!btleDeviceRegistered)
{
myNEO2Reader.registerListen();
btleDeviceRegistered = true;
}
}
}
else
{
String deviceName = btledevice.getName();
if (deviceName != null && deviceName.startsWith(BLE_Id))
{
BluetoothLEController.setBluetoothDevice(btledevice);
btleDeviceAddress = btledevice.getAddress();
if (!btleDeviceRegistered)
{
myNEO2Reader.registerListen();
btleDeviceRegistered = true;
}
}
}
}
}
};