7

How to react to directed advertising (ADV_DIRECT_IND == 0001) in Android?

There is a BLE-gadget which sends directed advertising to an Android phone (using hardcoded MAC address of the phone for now) and in my Android app I would like to react and to initiate a connection to the gadget and read the org.bluetooth.characteristic.location_and_speed value from the gadget:

screenshot

Please advise if it's possible by the means of Android 5 API.

4

2 回答 2

4

直接广告确实有效 - 至少与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 端的扫描类型——即扫描是否是定向的

于 2015-08-13T17:43:23.190 回答
1

部分回答未解决的问题:
我注意到ScanRecord.getBytes()对于定向扫描 ( ) 是空的 - 全部为 '\0' ADV_DIRECT_IND- 但否则将包含广告数据 ( ADV_IND)。

于 2017-01-16T20:39:26.280 回答