首页 > 解决方案 > Android BLE 与 MAC 地址连接

问题描述

我尝试将 Arduino 和 Android 手机与 BLE 连接。

但它不起作用。

我希望应用程序与具有特定名称和 MAC 地址的特定设备连接。

我声明Mac地址

private static String Adr = "D4:36:39:6F:7F:0E";

等等

private BluetoothGattCharacteristic characteristic;
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private Handler mHandler;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt mGatt;
private SharedPreferences setting;

并做了一些课程。

部分分类是

private ScanCallback mScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        Log.i("callbackType", String.valueOf(callbackType));
        Log.i("result", result.toString());
        btDevice = result.getDevice();

        if (btDevice != null && btDevice.getName() != null && btDevice.getName().contains("Device"))
            connectToDevice(btDevice);
    }

    @Override
    public void onBatchScanResults(List<ScanResult> results) {
        for (ScanResult sr : results) {
            Log.i("ScanResult - Results", sr.toString());
        }
    }

    @Override
    public void onScanFailed(int errorCode) {
        Log.e("Scan Failed", "Error Code: " + errorCode);
    }
};

private BluetoothAdapter.LeScanCallback mLeScanCallback =
    new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.i("onLeScan", device.toString());
                    connectToDevice(device);
                }
            });
        }
    };

我搜索了互联网并修改了

public void connectToDevice(BluetoothDevice device) {
    if (mGatt == null) {
        btDevice = mBluetoothAdapter.getRemoteDevice(CantusAdr); 
        mGatt = device.connectGatt(this, false, gattCallback);
    }
}

与 arduino 设备连接。

private ScanCallback mScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        Log.i("callbackType", String.valueOf(callbackType));
        Log.i("result", result.toString());
        btDevice = result.getDevice();

        if (btDevice != null && btDevice.getName() != null && btDevice.getName().contains("Device"))
            connectToDevice(btDevice);
    }

此代码用于连接具有 MAC 地址“D4:36:39:6F:7F:0E”的命名“设备”

应用程序正在运行。

它与一台设备连接,但不与“设备”“D4~~~”连接。

我该如何解决?

请帮我。

标签: androidarduinobluetooth-lowenergy

解决方案


如果您已经知道要连接的设备的地址,则无需进行蓝牙 LE 扫描。这应该足够了:

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("D4:36:39:6F:7F:0E");
device.connectGatt(this, false, gattCallback);

推荐阅读