我正在尝试通过代码进行配对,它仅适用于普通设备。如果我使用蓝牙扫描仪,它会与之配对,但设备无法工作,直到我进入 android 设置并选择输入设备复选框。我怎样才能通过代码做到这一点?
谢谢你。
这是我的配对代码:
public static BluetoothSocket createL2CAPBluetoothSocket(String address, int psm){
return createBluetoothSocket(TYPE_L2CAP, -1, false,false, address, psm);
}
// method for creating a bluetooth client socket
private static BluetoothSocket createBluetoothSocket(
int type, int fd, boolean auth, boolean encrypt, String address, int port){
try {
Constructor<BluetoothSocket> constructor = BluetoothSocket.class.getDeclaredConstructor(
int.class, int.class,boolean.class,boolean.class,String.class, int.class);
constructor.setAccessible(true);
BluetoothSocket clientSocket = (BluetoothSocket)
constructor.newInstance(type,fd,auth,encrypt,address,port);
return clientSocket;
}catch (Exception e) { return null; }
}
private void doPair(final BluetoothDevice device, final int deviceTag) {
try {
Method method = device.getClass().getMethod("createBond",
(Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e(LOG_TAG, "Cannot pair device", e);
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(
BluetoothDevice.EXTRA_BOND_STATE,
BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(
BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE,
BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED
&& prevState == BluetoothDevice.BOND_BONDING) {
Log.d(LOG_TAG, "Paired with new device");
if (listener != null) {
listener.onBluetoothPairedDeviceChange(bluetoothAdapter
.getBondedDevices().iterator().next()
.getName(), deviceTag);
}
context.unregisterReceiver(this);
} else if (state == BluetoothDevice.BOND_NONE
&& prevState == BluetoothDevice.BOND_BONDING) {
Log.d(LOG_TAG, "Cannot pair with new device");
if (listener != null) {
listener.onBluetoothStatusChange(BluetoothHelper.IDLE_STATUS);
}
context.unregisterReceiver(this);
}
}
}
};
IntentFilter intent = new IntentFilter(
BluetoothDevice.ACTION_BOND_STATE_CHANGED);
context.registerReceiver(mReceiver, intent);
}