/** 设备列表的单击响应函数,点击列表项,开始与该蓝牙设备建立连接 */ @SuppressLint("HandlerLeak") @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DeviceList remoteDeviceList = deviceList.getItem(position); deviceName = remoteDeviceList.getRemoteDeviceName(); bluetoothAdapter.cancelDiscovery(); // 停止查找设备 AcceptThread aThread = new AcceptThread(bluetoothAdapter, serverName, MY_UUID); aThread.start(); // 启动服务器线程 ConnectThread cThread = new ConnectThread(remoteDeviceList.getRemoteDevice(), MY_UUID, handler); cThread.start(); // 启动客户端线程 mConnectThread = cThread; tvinfo.setText(String.format("正在与%s建立连接...", deviceName)); // 注册一个Broadcast Receiver来监听BluetoothDevice.ACTION_ACL_DISCONNECTED,即与远程设备建立连接失败 registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)); }