我解决了使用32Feet通过蓝牙发送文本的问题。我只是为我的连接创建了一个GUID,并在两个(发送者/接收者)端使用相同的ID。我的发件人是Android客户端,接收者是WPF应用程序。我发送字符串作为byte的流。这是代码:
private void SetupBluetoothListner() { _messageServiceId = new Guid("{646171EA-EA18-4CCF-8D7A-C57D46991775}"); _isBluetoothRecieverStarted = true; if (_cancelToken != null && _messageListener != null) { this.Dispose(true); } _cancelToken = new CancellationTokenSource(); _messageListener = new BluetoothListener(_messageServiceId) { ServiceName = Constants.BluetoothStringMessageService }; } private void BluetoothListener(CancellationTokenSource cancelToken, BluetoothListener bluetoothListener) { try { while (true) { using (var client = bluetoothListener.AcceptBluetoothClient()) { if (cancelToken.IsCancellationRequested) { return; } using (var streamReader = new StreamReader(client.GetStream())) { try { var content = streamReader.ReadToEnd(); if (!string.IsNullOrEmpty(content)) { MessageReceiver(content); } } catch (IOException ex) { client.Close(); break; } } } } } catch (Exception ex) { MessageBox.Show(ex.Message, Constants.ErrorAtReceivingStringMessage, MessageBoxButton.OK); } } private bool SendData(Device device, byte[] content) { using (var bluetoothClient = new BluetoothClient()) { try { var endpoint = new BluetoothEndPoint(device.DeviceInfo.DeviceAddress, _messageServiceId); bluetoothClient.Connect(endpoint); var bluetoothStream = bluetoothClient.GetStream(); if (bluetoothClient.Connected && bluetoothStream != null) { bluetoothStream.Write(content, 0, content.Length); bluetoothStream.Flush(); bluetoothStream.Close(); return true; } return false; } catch (Exception ex) { // TODO: handle exception } } return false; }
------------ Android客户端代码-------
private UUID serviceUUID = UUID.fromString("0e6114d0-8a2e-477a-8502-298d1ff4b4ba"); public void OpenSocket(BluetoothDevice currentDevice) { try { BluetoothSocket socket = currentDevice.createRfcommSocketToServiceRecord(serviceUUID); socket.connect(); outputStream = socket.getOutputStream(); inputStream = socket.getInputStream(); } catch(Exception ex){ Log.d("socket","socket" + ex.getMessage()); } } public void SendData(String message) { try{ outputStream.write(message.getBytes()); } catch(Exception ex){ } }
我仍然坚持使用ObexObjectPush捕获数据发送的问题。