There is one very serious problem. My application should recognize when the connection is broken (so far only due to the fact that the user knocked out bluetooth).
I did this:
This is a separate stream (to check if the bluetooth works every 5 seconds).
@Override public void run() { while(true) { try { newCheck = new BluetoothCheck(bluetooth); if (!newCheck.isBluetoothEnabled()) textView.setText("Отсутствует подключение..."); else textView.setText("Подключение установлено"); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } And here the necessary module is initialized (in my case, hc-06) and starts the stream I need.
public void tryConnectToWatch() { if (bluetooth.isEnabled()) { try { BluetoothDevice device = bluetooth.getRemoteDevice("20:16:08:16:14:57"); Method m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class}); clientSocket = (BluetoothSocket) m.invoke(device, 1); clientSocket.connect(); Toast.makeText(getApplicationContext(), "Браслет подключен успешно.", Toast.LENGTH_LONG).show(); Thread thread = new Thread(this); thread.start(); } } } There are no syntax errors, but nothing happens either. It puts me once - the connection is established and everything, then every 5 seconds there is no verification.
The BluetoothCheck class was written by myself and yes, I know that it is not needed, I created it after the last attempt. Here is the code:
class BluetoothCheck{ BluetoothAdapter bluetoothAdapter; public BluetoothCheck(BluetoothAdapter bluetoothAdapter) { this.bluetoothAdapter = bluetoothAdapter; } public boolean isBluetoothEnabled() { if (bluetoothAdapter.isEnabled()) { return true; } else {return false;} } }