我无法通过Android手机连接蓝牙模块。我使用这个代码编写了几个应用程序,它们似乎都运行良好,然后突然间没有一个工作(即使我没有更改其中任何一个的代码)。这对其他蓝牙模块来说不是问题,因为我仍然可以很好地连接Blueterm应用程序。所以我想知道可能是什么问题。
public void connect() throws IOException {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
// ensure that the device is bluetooth enabled
if (adapter != null) {
// enable the bluetooth adapter (if not done so already)
if (!adapter.isEnabled())
BluetoothAdapter.getDefaultAdapter().enable();
// connect to hardcoded device
BluetoothDevice device = adapter.getRemoteDevice(MAC_ADDRESS);
Log.d("", device.toString());
pairDevice(device);
ParcelUuid[] uuids = device.getUuids();
uuids = device.getUuids();
socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
}
}
public boolean isConnected() {
return socket.isConnected();
}
private void disconnect() {
BluetoothAdapter.getDefaultAdapter().disable();
}
private void pairDevice(BluetoothDevice device) {
try {
Log.d("pairDevice()", "start pairing...");
Method m = device.getClass().getMethod("createBond", (Class[])null);
m.invoke(device, (Object[])null);
Log.d("pairDevice()", "pairing finished.");
} catch(Exception e) {
Log.e("pairDevice()", e.getMessage());
}
}
connect()方法中的socket.connect()行引发IOError,我不知道原因。
这是Logcat输出:
D/pairDevice()(9589): start pairing...
D/pairDevice()(9589): pairing finished.
D/BluetoothUtils(9589): isSocketAllowedBySecurityPolicy start : device null
W/BluetoothAdapter(9589): getBluetoothService() called with no BluetoothManagerCallback
D/BluetoothSocket(9589): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[66]}