使用BluetoothAdapter的getRemoteDevice()连接蓝牙

时间:2015-12-09 10:49:36

标签: android bluetooth android-bluetooth

我想手动连接蓝牙设备及其MAC地址,因为它更快,我确切知道连接哪个MAC。

我使用此方法获取BluetoothDevice:http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getRemoteDevice%28byte[]%29

但Android doc并未说明在创建BluetoothDevice对象之前Android是否确保设备在范围内。 你有这个信息吗?

我的代码可以自动连接设备,我想在尝试连接之前检查目标是否在范围内,但是没有执行大扫描(可能很长...)

1 个答案:

答案 0 :(得分:0)

当本地设备使用BluetoothSocket连接到远程设备时,需要例外。

如果远程设备不在范围内,则找不到

private class ConnectThread extends Thread {

    public ConnectThread(BluetoothDevice device, boolean isSecure, UUID sharedUUID) throws IncorrectSetupException {
        try {
            //Secure connections requires to get paired before connect
            //Insecure connections allows to connect without pairing
            if (isSecure) {
                mSocket = device.createRfcommSocketToServiceRecord(sharedUUID);
            } else {
                mSocket = device.createInsecureRfcommSocketToServiceRecord(sharedUUID);
            }
        } catch (IOException e) {
            //Is there some problem with the setup?
        }
    }

    public void run() {
        try {
            mSocket.connect();
        } catch (IOException e) {
            //If device is not found, this exception is throwed
        }
    }

}