直接广告确实有效 - 至少与HTC M8手机和 Android 5.0(API 级别 21 及更高版本)一起使用。
解决方案是将设备地址添加到ScanFilter。
如果您将过滤器留空,则不会调用扫描回调。
这是我的工作代码:
public static final String TAG = "My_BLE_app";
public static final String DEVICE_1 = "D4:BE:84:72:5B:8E";
public static final String DEVICE_2 = "C4:39:07:19:60:E2";
private Context mContext;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mScanner;
private ScanSettings mSettings;
private List<ScanFilter> mFilters = new ArrayList<ScanFilter>();
首先是初始化BLE的方法:
public boolean init() {
BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null)
return false;
mScanner = mBluetoothAdapter.getBluetoothLeScanner();
mSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
mFilters.add(new ScanFilter.Builder().setDeviceAddress(DEVICE_1).build());
mFilters.add(new ScanFilter.Builder().setDeviceAddress(DEVICE_2).build());
return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}
然后是扫描回调:
private ScanCallback mDirectedScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
processResult(result);
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult result: results) {
processResult(result);
}
}
private void processResult(ScanResult result) {
BluetoothDevice device = result.getDevice();
if (device == null)
return;
String address = device.getAddress();
if (!BluetoothAdapter.checkBluetoothAddress(address))
return;
int rssi = result.getRssi();
Log.d(TAG, "address=" + address + ", rssi=" + rssi);
// TODO connect to the device in under 1 second
}
};
最后是开始扫描的代码:
mScanner.startScan(mFilters, mSettings, mDirectedScanCallback);
一个问题仍然悬而未决:
我不知道如何检测 Android 端的扫描类型——即扫描是否是定向的。