1. 首页
  2. 移动开发
  3. Android
  4. Android平台的蓝牙连接—客户端-android通信

Android平台的蓝牙连接—客户端-android通信

上传者: 2024-07-06 01:48:54上传 PPT文件 2.27MB 热度 8次
Android平台的蓝牙连接—客户端连接为了初始化一个与远端设备的连接,需要先获取代表该设备的一个bluetoothdevice对象。通过bluetoothdevice对象来获取bluetoothsocket并初始化连接: t使用bluetoothdevice里的方法createRfcommSocketToServiceRecord(UUID)来获取bluetoothsocket。UUID就是匹配码。 t调用connect()方法。如果远端设备接收了该连接,他们将在通信过程中共享RFFCOMM信道,并且connect()方法返回。示例代码见备注。注意:conncet()方法也是阻塞调用,一般建立一个独立的线程中来调用该方法。在设备discover过程中不应该发起连接connect(),这样会明显减慢速度以至于连接失败。且数据传输完成只有调用close()方法来关闭连接,这样可以节省系统内部资源。 private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { // Use a temporary object that is later assigned to mmSocket, // because mmSocket is final BluetoothSocket tmp = null; mmDevice = device; // Get a BluetoothSocket to connect with the given BluetoothDevice try { // MY_UUID is the app's UUID string, also used by the server code tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { } mmSocket = tmp; } public void run() { // Cancel discovery because it will slow down the connection mAdapter.cancelDiscovery(); try { // Connect the device through the socket. This will block // until it succeeds or throws an exception mmSocket.connect(); } catch (IOException connectException) { // Unable to connect; close the socket and get out try { mmSocket.close(); } catch (IOException closeException) { } return; } // Do work to manage the connection (in a separate thread) manageConnectedSocket(mmSocket); } /** Will cancel an in-progress connection, and close the socket */ public void cancel() { try { mmSocket.close(); } catch (IOException e) { } } *
用户评论