我的应用正在尝试同时连接蓝牙模块和发送/接收数据。但有时会抛出以下错误(通常在GC调用之后发生): -
12-15 19:06:15.559: D/dalvikvm(22875): GC_FOR_ALLOC freed 3925K, 25% free 11400K/15096K, paused 28ms, total 28ms
12-15 19:06:15.559: E/System(22875): Uncaught exception thrown by finalizer
12-15 19:06:15.559: E/System(22875): java.io.IOException: socket not created
12-15 19:06:15.559: E/System(22875): at android.net.LocalSocketImpl.shutdownInput(LocalSocketImpl.java:392)
12-15 19:06:15.559: E/System(22875): at android.net.LocalSocket.shutdownInput(LocalSocket.java:206)
12-15 19:06:15.559: E/System(22875): at android.bluetooth.BluetoothSocket.close(BluetoothSocket.java:462)
12-15 19:06:15.559: E/System(22875): at android.bluetooth.BluetoothSocket.finalize(BluetoothSocket.java:229)
12-15 19:06:15.559: E/System(22875): at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:187)
12-15 19:06:15.559: E/System(22875): at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:170)
12-15 19:06:15.559: E/System(22875): at java.lang.Thread.run(Thread.java:841)
这个未被捕获的异常会反复抛出几次,因此我的应用程序停止响应。
出现此错误的可能原因是什么?我试图解决它,但找不到确切的问题。请帮忙。
我还附上了我用来连接蓝牙模块的代码。我正在使用AsyncTask来执行此操作..
//global variable
BluetoothSocket mBSocket;
// inside doInBackground() function
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
try {
for (BluetoothDevice bt : mBluetoothAdapter.getBondedDevices()) {
if (bt.getName().equalsIgnoreCase("MY_DEVICE_BT_NAME")) {
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(bt.getAddress());
mBluetoothAdapter.cancelDiscovery(); // We have named our
// device so
// cancel search
mBSocket = device
.createRfcommSocketToServiceRecord(SPP_UUID);
if(!mBSocket.isConnected()) {
mBSocket.connect();
}
return mBSocket;
}
}
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
} else
return null;
答案 0 :(得分:2)
我已修改代码以连接到我的蓝牙模块,正确处理异常,因为我没有遇到任何此类错误,正如我在问题中所描述的那样。
//global variable
BluetoothSocket mBSocket;
// inside doInBackground() function
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter.isEnabled()) {
try {
for(BluetoothDevice bt: mBluetoothAdapter.getBondedDevices()) {
if(bt.getName().equalsIgnoreCase(params[0])) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bt.getAddress());
mBluetoothAdapter.cancelDiscovery();
mBSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
mBSocket.connect();
return mBSocket;
}
}
} catch(IOException e) {
if(mBSocket != null) {
try {
mBSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
mBSocket = null;
}
e.printStackTrace();
return null;
}
}
return null;