После того как вы подключитесь к устройству Bluetooth, у каждого из них появится значок BluetoothSocket. Теперь вы можете обмениваться информацией между устройствами. Общая процедура переноса данных с помощью BluetoothSocket выглядит следующим образом:
Получите
InputStreamиOutputStream, которые обрабатывают передачу данных через сокет, используяgetInputStream()иgetOutputStream()соответственно.Чтение и запись данных в потоки с помощью
read(byte[])иwrite(byte[]).
Конечно, есть детали реализации, которые необходимо учитывать. В частности, для чтения из потока и записи в него следует использовать выделенный поток.
Это важно, поскольку методы read(byte[]) и write(byte[]) блокируют вызовы. Метод read(byte[]) блокирует поток до тех пор, пока не появится что-то, что можно прочитать. Метод write(byte[]) обычно не блокирует, но может блокировать управление потоком, если удаленное устройство недостаточно быстро вызывает read(byte[]) и в результате промежуточные буферы заполняются. Поэтому основной цикл в потоке должен быть посвящен чтению из InputStream.
Для записи в OutputStream можно использовать отдельный общедоступный метод в потоке.
Пример
Ниже приведен пример того, как можно передавать данные между двумя устройствами, подключенными по Bluetooth.
Kotlin
private const val TAG = "MY_APP_DEBUG_TAG" // Defines several constants used when transmitting messages between the // service and the UI. const val MESSAGE_READ: Int = 0 const val MESSAGE_WRITE: Int = 1 const val MESSAGE_TOAST: Int = 2 // ... (Add other message types here as needed.) class MyBluetoothService( // handler that gets info from Bluetooth service private val handler: Handler) { private inner class ConnectedThread(private val mmSocket: BluetoothSocket) : Thread() { private val mmInStream: InputStream = mmSocket.inputStream private val mmOutStream: OutputStream = mmSocket.outputStream private val mmBuffer: ByteArray = ByteArray(1024) // mmBuffer store for the stream override fun run() { var numBytes: Int // bytes returned from read() // Keep listening to the InputStream until an exception occurs // or read() returns -1 while (true) { // Read from the InputStream. try { numBytes = mmInStream.read(mmBuffer) if (numBytes < 0) { Log.i(TAG, "returns -1, Input stream disconnected") break } } catch (e: IOException) { Log.d(TAG, "Input stream was disconnected", e) break } // Send the obtained bytes to the UI activity. val readMsg = handler.obtainMessage( MESSAGE_READ, numBytes, -1, mmBuffer) readMsg.sendToTarget() } } // Call this from the main activity to send data to the remote device. fun write(bytes: ByteArray) { try { mmOutStream.write(bytes) } catch (e: IOException) { Log.e(TAG, "Error occurred when sending data", e) // Send a failure message back to the activity. val writeErrorMsg = handler.obtainMessage(MESSAGE_TOAST) val bundle = Bundle().apply { putString("toast", "Couldn't send data to the other device") } writeErrorMsg.data = bundle handler.sendMessage(writeErrorMsg) return } // Share the sent message with the UI activity. val writtenMsg = handler.obtainMessage( MESSAGE_WRITE, -1, -1, mmBuffer) writtenMsg.sendToTarget() } // Call this method from the main activity to shut down the connection. fun cancel() { try { mmSocket.close() } catch (e: IOException) { Log.e(TAG, "Could not close the connect socket", e) } } } }
Java
public class MyBluetoothService { private static final String TAG = "MY_APP_DEBUG_TAG"; private Handler handler; // handler that gets info from Bluetooth service // Defines several constants used when transmitting messages between the // service and the UI. private interface MessageConstants { public static final int MESSAGE_READ = 0; public static final int MESSAGE_WRITE = 1; public static final int MESSAGE_TOAST = 2; // ... (Add other message types here as needed.) } private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; private byte[] mmBuffer; // mmBuffer store for the stream public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the input and output streams; using temp objects because // member streams are final. try { tmpIn = socket.getInputStream(); } catch (IOException e) { Log.e(TAG, "Error occurred when creating input stream", e); } try { tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "Error occurred when creating output stream", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { mmBuffer = new byte[1024]; int numBytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs. while (true) { try { // Read from the InputStream. numBytes = mmInStream.read(mmBuffer); if (numBytes < 0) { Log.i(TAG, "Read return -1, Input stream disconnected"); break; } // Send the obtained bytes to the UI activity. Message readMsg = handler.obtainMessage( MessageConstants.MESSAGE_READ, numBytes, -1, mmBuffer); readMsg.sendToTarget(); } catch (IOException e) { Log.d(TAG, "Input stream was disconnected", e); break; } } } // Call this from the main activity to send data to the remote device. public void write(byte[] bytes) { try { mmOutStream.write(bytes); // Share the sent message with the UI activity. Message writtenMsg = handler.obtainMessage( MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer); writtenMsg.sendToTarget(); } catch (IOException e) { Log.e(TAG, "Error occurred when sending data", e); // Send a failure message back to the activity. Message writeErrorMsg = handler.obtainMessage(MessageConstants.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString("toast", "Couldn't send data to the other device"); writeErrorMsg.setData(bundle); handler.sendMessage(writeErrorMsg); } } // Call this method from the main activity to shut down the connection. public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "Could not close the connect socket", e); } } } }
После того как конструктор получит необходимые потоки, поток будет ожидать поступления данных через InputStream. Когда read(byte[]) возвращает данные из потока, они отправляются в основное действие с помощью элемента Handler из родительского класса. Затем поток ожидает, пока из InputStream не будет считано больше байтов.
Чтобы отправить исходящие данные, вызовите метод write() потока из основного действия и передайте байты, которые нужно отправить. Этот метод вызывает write(byte[]), чтобы отправить данные на удаленное устройство. Если при вызове write(byte[]) возникает ошибка IOException, поток отправляет всплывающее уведомление в основное действие, сообщая пользователю, что устройство не смогло отправить указанные байты на другое (подключенное) устройство.
Метод cancel() потока позволяет в любой момент закрыть соединение, закрыв BluetoothSocket. Всегда вызывайте этот метод, когда вы закончили использовать Bluetooth-подключение.
Пример использования Bluetooth API можно найти в приложении Bluetooth Chat на GitHub.