I have an Android application that connects to a paired device. The problem is that if I don't have this device enabled before the application starts, it never works.
The only case that works is when the device is on and then I start the application. If I start the application and next the device, it never connects.
Here is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check if the system supports Bluetooth Low Energy
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "BLE Not Supported", Toast.LENGTH_SHORT).show();
finish();
}
// Take the system BLE adapter
bleAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
// Enable Bluetooth in case it's off.
if (bleAdapter == null || !bleAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
start_microbit();
}
private void start_microbit() {
// Get paired devices.
Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
// Connect to Micro:Bit (the only one paired device)
device.connectGatt(this, true, new BluetoothGattCallback() {
// Check if it connects or disconnects from the Micro:Bit
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
runOnUiThread(new Runnable() {
public void run() {
((TextView) findViewById(R.id.state)).setText("Connected to Micro:Bit");
((TextView) findViewById(R.id.state)).setTextColor(Color.GREEN);
}
});
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
runOnUiThread(new Runnable() {
public void run() {
((TextView) findViewById(R.id.state)).setText("Not connected");
((TextView) findViewById(R.id.state)).setTextColor(Color.RED);
}
});
gatt.disconnect();
break;
}
}
});
}
}