我在使用 Android 4 (ICS) 时遇到问题 我的蓝牙应用程序连接到串行设备就像在 Android 3 上的魅力一样。
但是,在使用 Android 4 时,每次我连接到(已经配对的)设备时,它都会显示“配对”对话框。
用户必须一遍又一遍地重新输入相同的密码。有什么方法可以抑制 Android 4 中的这种行为吗?它是一个新的错误吗?有解决办法吗?BluetoothDevice 是否需要对 Android 4 进行某种适应?我究竟做错了什么?
/**
* Start the ConnectThread to initiate a connection to a remote bluetoothDevice.
*/
public synchronized InitResponse init() {
if (D) Log.d(TAG, "init to: " + bluetoothDevice);
setState(State.CONNECTING);
try {
if (D) Log.i(TAG, "Trying to create RfcommSocket using reflection");
Method m = bluetoothDevice.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
bluetoothSocket = (BluetoothSocket)m.invoke(bluetoothDevice, 1);
} catch (Exception e) {
if (D) Log.w(TAG, "Reflection failed.", e);
if (D) Log.i(TAG, "Trying to create RfcommSocket using UUID");
try {
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(READER_UUID);
} catch (IOException e2) {
Log.e(TAG, "create() failed", e2);
disconnect();
return InitResponse.READER_NOT_FOUND;
}
}
if (D) Log.i(TAG, "Bluetooth Socket: " + bluetoothSocket);
if (D) Log.i(TAG, "Trying to connect.");
try {
bluetoothAdapter.cancelDiscovery();
if (D) Log.i(TAG, "Cancelled discovery.");
if (D) Log.i(TAG, "Attempting to connect.");
bluetoothSocket.connect(); // Causes pairing dialog everytime I call it.
} catch (IOException e) {
if (D) Log.w(TAG, "Error while connecting.");
// Close the socket
try {
bluetoothSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
} finally {
disconnected();
}
return InitResponse.CONNECTION_ERROR;
}
if(D) Log.d(TAG, "Connected to bluetoothReader " + bluetoothDevice + " established.");
try {
inputStream = bluetoothSocket.getInputStream();
if(D) Log.d(TAG, "Input Stream: " + inputStream);
outputStream = bluetoothSocket.getOutputStream();
if(D) Log.d(TAG, "Output Stream: " + outputStream);
} catch (IOException e) {
Log.e(TAG, "Temp sockets not created", e);
disconnected();
return InitResponse.CONNECTION_ERROR;
}
if (D) Log.i(TAG, "Setting state to CONNECTED");
setState(State.CONNECTED);
if (D) Log.i(TAG, "Init successfull.");
return InitResponse.SUCCESS;
}
提前致谢
顺便说一句:如何确保在连接之前停止从平板电脑到此蓝牙设备的所有其他连接?