确保蓝牙控制器已经开启并处于可连接状态。
开启蓝牙扫描,并在扫描结果中找到目标控制器,使用如下代码:
// 检查蓝牙是否已经开启
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// 开始扫描蓝牙设备
bluetoothAdapter.startDiscovery();
// 监听扫描结果,找到目标蓝牙设备
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName().equals("TargetDeviceName")) {
// 连接目标设备
connectToDevice(device);
// 取消扫描
bluetoothAdapter.cancelDiscovery();
}
}
}
};
// 连接蓝牙设备
private void connectToDevice(BluetoothDevice device) {
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
// 在Manifest中添加以下权限
// 设置当前应用可以在Android设备上使用外部输入设备
InputManager inputManager = (InputManager) getSystemService(Context.INPUT_SERVICE);
inputManager.registerInputDeviceListener(new InputDeviceListener() {
@Override
public void onInputDeviceAdded(int deviceId) {
InputDevice device = InputDevice.getDevice(deviceId);