我正在尝试使用以下代码连接到蓝牙设备(HC06),但我无法弄清楚问题出在哪里,根据日志,问题是bluetoothAdapter.cancelDiscovery();
之后的说明,我没有不知道是否需要在单独的线程或AsyncTask中运行它,因为当前在主线程中被调用,因此不胜感激。
private void ConnectToBTDialog(){
AlertDialog.Builder builder0=new AlertDialog.Builder(this);
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
final String[] names = new String[pairedDevices.size()];
final String[] addresses = new String[pairedDevices.size()];
if (pairedDevices.size() > 0) {
int j=0;
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
names[j]=device.getName();
addresses[j]=device.getAddress();
j++;
}
builder0.setItems(names, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
address=addresses[i];
Log.e("ConnectToBTDialog", "Connecting to : Mac name : "+ address +" "+ names[i]);
Set<BluetoothDevice> pairedDevices2 = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices2) {
if (device.getAddress().equals(address)){
try {
btSocket=device.createRfcommSocketToServiceRecord(myUUID);
bluetoothAdapter.cancelDiscovery();
btSocket.connect();
inputStream=btSocket.getInputStream();
outputStream=btSocket.getOutputStream();
Toast.makeText(Home.this, "connected to "+ device.getName(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Log.e("BT", " can't connect ");
}
}
}
}
});
}
builder0.setTitle("Choose a device");
Dialog dialog0=builder0.create();
dialog0.show();
}
错误日志如下:
09-18 13:18:53.975 28834-28834/com.example.com...E/ConnectToBTDialog: Connecting to : Mac name : 98:D3:31:FB:41:BE HC-06
09-18 13:18:53.985 29163-29268/? E/BluetoothAdapterService: This is not a scanning status. cancelDiscovery() will be not called.
09-18 13:18:55.627 29163-29224/? E/BluetoothServiceJni: Callback env check fail: env: 0x0, callback: 0xaa0a3420 Callback: 'remote_device_properties_callback' is not called on the correct thread
09-18 13:18:55.637 29163-29205/? E/BluetoothRemoteDevices: aclStateChangeCallback: State:Connected to Device:98:D3:31:FB:41:XX, linktype is 1
09-18 13:18:55.697 29163-29224/? E/bt_btif_sock_rfcomm: SDP - Failed to look up a channel number to connect to
09-18 13:18:55.697 29163-29261/? E/bt_btif_sock_rfcomm: find_rfc_slot_by_id unable to find RFCOMM slot id: 7
09-18 13:18:55.697 28834-28834/com.example.com.. E/BT: can't connect