如何在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();
}
};
另一个问题。 如何等待完成扫描?
答案 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++;
}