我目前正在设计一款需要连接到设备,写入/读取数据以及可靠地关闭连接的应用。目前我有写/读固体。我断开连接然后重新连接是非常不可靠的,并且经常会使手机崩溃..有时候是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。问题是,当我在第二次连接尝试时重新连接它时,它将只是坐在那里或完全崩溃手机,导致几次重启。
有没有人在这里有任何建议?它非常令人沮丧。任何帮助将不胜感激!!
谢谢你,杰克! TxAg
答案 0 :(得分:0)
你用的是哪款手机?什么OS?看到这个答案: Disconnect a bluetooth socket in Android
关闭实际上在某些HTC 2.1update1手机上无法正常工作