保存可发现的蓝牙LE设备列表?

时间:2016-04-26 10:18:50

标签: android bluetooth runnable android-bluetooth android-ble

如何在Android中保存可发现的BLE设备列表?

按照 startDeviceScan()方法执行:

private String[][] mNearestDevices;
// ...

public String[][] startDeviceScan() {
    Log.i(TAG, "Start device scan");

    mNearestDevices = new String[n][2];
    mCounter = 0;

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mBleScanCallback);
        }
    }, SCAN_PERIOD);

    mScanning = true;
    mBluetoothAdapter.startLeScan(mBleScanCallback);

    return mNearestDevices;
}

这是设备扫描回调

private BluetoothAdapter.LeScanCallback mBleScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG, "Name: " + device.getName() + " (" + device.getAddress() + ")");
                        mNearestDevices[mCounter][0] = device.getName();
                        mNearestDevices[mCounter][1] = device.getAddress();
                    }
                };
                r.run();
            }
        };

另一个问题。 如何等待完成扫描?

1 个答案:

答案 0 :(得分:0)

您必须更改onLeScan方法:

@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord)
{

    Log.i(TAG, "Name: " + device.getName() + " (" + device.getAddress() + ")");
    mNearestDevices[mCounter][0] = device.getName();
    mNearestDevices[mCounter][1] = device.getAddress();
    mCounter++;
}