繁体   English   中英

如何使用 Android Java 有效地连接到蓝牙设备套接字?

[英]How to effectively connect to Bluetooth Device socket with Android Java?

我正在尝试使用 Android Java 将我的蓝牙应用程序连接到我的 PC。 将我的应用程序连接到 PC 套接字后,我可以发送诸如Say Hello之类的消息。 我的应用程序使用位置和蓝牙 API 成功扫描了范围内的蓝牙设备。 它发现了我的 PC,我从为我的 PC 发现的蓝牙设备配置文件中获取了我的 PC 的 UUID。 我将我的 PC 的 UUID 公开为 logcat 上的蓝牙设备,只要您在调用它之前取消发现,它看起来像device.getUUIDs不会返回 null。 这是打印在我的 logcat 上的 UUID 字符串

BluetoothClient.BluetoothClient D/UUID: 0000110a-0000-1000-8000-00805f9b34fb

下面的代码显示了我如何尝试连接到 PC 蓝牙设备套接字

//check if the device is already bonded and attempt to connect to its socket if it is exposed
 if (dev.BondState == Bond.Bonded){
  //device is a bluetooth device on my list I grabbed from the broadcast receiver
  //grab the UUID of the discovered bluetooth device
  UUID MYUUID = dev.GetUuids()[0].Uuid;
  //create a bluetooth socket using the UUID for connection purposes
  BluetoothSocket socket = dev.CreateRfcommSocketToServiceRecord(MYUUID);
  //connect to the socket
  socket.Connect();
 } 

编写的代码不会引发任何异常,应用程序也不会崩溃,此信息打印在我的 logcat 上。

 D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
 // I do not know what the above is and what device is null 
 I/BluetoothSocket: connect() for device F894C2 called by pid: 2822
 W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
 //if a bluetooth manager callback is needed for the socket creation, how do attach the callback to my code to make this work, Thank You.

有关基本代码https://github.com/petzval/btferret ,请参阅此处 README.md 文档中的第 5.5.3 节。 函数 instream.read 和 outstream.write 交换串行数据。

 byte[] dat;
 String s;
 int len;

 dat = new byte[32];
 s = "Hello\n";
 len = s.length();
 for(n = 0 ; n < len ;++n)
   dat[n] = s.charAt(n);
 
 outstream.write(dat,0,len);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM