我目前正在设计一个应用程序,需要连接到设备,写入/读取数据,并可靠地关闭连接。目前,我的写/读操作是可靠的。我断开连接然后再重新连接是非常不可靠的,而且经常会导致电话崩溃。有时还会出现日食。我已经看了无数的文章试图弄清楚这一点..没有运气..。
*CONNECT函数**
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();
}
}因此,断开连接成功,并返回所有内容为空。问题是,当我重新连接时,它在第二次连接尝试时阻塞,并将只是坐在那里或完全崩溃的手机,导致几次重启。
这里有人有什么建议吗?这是非常令人沮丧的。任何帮助都将不胜感激!
谢谢你,谢谢!TxAg
发布于 2010-08-21 04:38:40
你用的是什么手机?什么操作系统?请看这个答案:Disconnect a bluetooth socket in Android
实际上,close在某些HTC 2.1update1手机上无法正常工作
https://stackoverflow.com/questions/3525753
复制相似问题