[英]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.