gpt4 book ai didi

安卓蓝牙 : Connect()/Disconnect()

转载 作者:行者123 更新时间:2023-11-29 14:10:45 24 4
gpt4 key购买 nike

我目前正在设计一个应用程序,它需要连接到设备、写入/读取数据并可靠地关闭连接。目前,我有写/读实体。我的断开连接然后重新连接非常不可靠,实际上经常使手机崩溃,有时甚至使 Eclipse 崩溃。

连接功能

public boolean connect()
{
ConfigData.getInstance();
BluetoothSocket tmp = null;
BluetoothDevice device = ConfigData.m_SharedBluetoothDevice;
Method m;
try {

tmp = device.createRfcommSocketToServiceRecord(MY_UUID);//(BluetoothSocket)
m.invoke(device, 1);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
ConfigData.m_SharedBluetoothSocket = tmp;
try {
ConfigData.m_SharedBluetoothSocket.connect();
ConfigData.bIsBTConnected = true;
} catch (IOException e) {
try {
closeSocket();
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
e.printStackTrace();
} catch (IllegalAccessException e1) {
e.printStackTrace();
} catch (InvocationTargetException e1) {
e.printStackTrace();
}
ConfigData.m_SharedBluetoothSocket = tmp;
try {
ConfigData.m_SharedBluetoothSocket.connect();
ConfigData.bIsBTConnected = true;
} catch (IOException e1) {
ConfigData.m_BluetoothException += e1.toString();
ConfigData.bIsBTConnected = false;
return false;

}
e.printStackTrace();
return true;
}
return true;
}

断开功能

 public void destroySocket()
{
try {
if(m_InStream != null)
{
m_InStream.close();
m_InStream = null;
}
if(m_OutStream != null)
{
m_OutStream.close();
m_OutStream = null;
}
if(ConfigData.m_SharedBluetoothSocket != null)
{
ConfigData.m_SharedBluetoothSocket.close();
ConfigData.m_SharedBluetoothSocket = null;
}
if(m_InStream == null && m_OutStream == null && ConfigData.m_SharedBluetoothSocket == null)
{
ConfigData.bIsBTConnected = false;
}
} catch (IOException e1) {
m_InStream = null;
m_OutStream = null;
ConfigData.m_SharedBluetoothSocket = null;
e1.printStackTrace();
}
}

因此断开连接成功并返回所有内容 null。问题是,当我重新连接时,它会在第二次连接尝试时阻塞,并且要么只是停在那里,要么完全使手机崩溃,导致多次重启。

这里有人有什么建议吗?

最佳答案

你用的是什么手机?什么操作系统?看到这个答案: Disconnect a bluetooth socket in Android

关闭实际上在某些 HTC 2.1update1 手机上无法正常工作

关于安卓蓝牙 : Connect()/Disconnect(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3525753/

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