gpt4 book ai didi

android - 连接到安卓蓝牙 socket

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:42 25 4
gpt4 key购买 nike

您好,我正在尝试创建一个 Android 应用程序,它将连接到我想向其发送数据的 Blue SMiRF 蓝牙加密狗。我已经阅读了开发人员页面并查看了多个不同的示例,但是我目前在创建到套接字的连接时遇到了问题。代码的蓝牙部分几乎来 self 能够找到的示例。当尝试连接到蓝牙加密狗时,应用程序会强制关闭,因为我没有正确处理一些错误。但是,我也曾尝试使用该应用程序仅连接到另一台 PC,但由于某种原因无法正确建立连接,即使我在运行该应用程序之前已经通过蓝牙设置与该设备配对。我已经在下面发布了一些我认为可能是我的问题的更重要的代码。任何帮助将不胜感激,如果我应该发布任何其他代码,请告诉我。

protected void connect(BluetoothDevice device) {
//BluetoothSocket socket = null;
try {
//Create a Socket connection: need the server's UUID number of registered

socket = device.createRfcommSocketToServiceRecord(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));



socket.connect();
Log.d("EF-BTBee", ">>Client connectted");

InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
outputStream.write(new byte[] { (byte) 0xa0, 0, 7, 16, 0, 4, 0 });


new Thread() {
public void run() {
while(true)
{
try {
Log.d("EF-BTBee", ">>Send data thread!");
OutputStream outputStream = socket.getOutputStream();
outputStream.write(new byte[] { (byte) 0xa2, 0, 7, 16, 0, 4, 0 });
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
}
}
};
}.start();

} catch (IOException e) {
Log.e("EF-BTBee", "", e);
} finally {
if (socket != null) {
try {
Log.d("EF-BTBee", ">>Client Close");
socket.close();
finish();
return ;
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
}
}
}
}`

我也试过用

Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});

socket = (BluetoothSocket) m.invoke(device, 1);

而不仅仅是上面的“socket =”行,仍然没有成功。

最佳答案

如果设备已经配对,那么你可以使用

if(device.getBondState()==device.BOND_BONDED){
Log.d(TAG,device.getName());
//BluetoothSocket mSocket=null;
try {
mSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.d(TAG,"socket not created");
e1.printStackTrace();
}
try{
mSocket.connect();
}
catch(IOException e){
try {
mSocket.close();
Log.d(TAG,"Cannot connect");
} catch (IOException e1) {
Log.d(TAG,"Socket not closed");
e1.printStackTrace();
}
}

供 MY_UUID 使用

private static final UUID MY_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB");

关于android - 连接到安卓蓝牙 socket ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20009565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com